在C++中,可以使用std::swap函數(shù)來(lái)交換兩個(gè)變量的值。以下是使用std::swap函數(shù)的示例代碼:
#include <iostream>
#include <algorithm>
int main() {
int a = 5;
int b = 10;
std::cout << "Before swapping: a = " << a << ", b = " << b << std::endl;
std::swap(a, b);
std::cout << "After swapping: a = " << a << ", b = " << b << std::endl;
return 0;
}
運(yùn)行上面的代碼將輸出:
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5
可以看到,使用std::swap函數(shù)可以輕松交換兩個(gè)變量的值。