swap
是一个标准库函数。C++ 提供了两种 swap
函数:
std::swap
函数:位于头文件<utility>
中,用于交换两个变量的值。- 容器的成员函数
swap
:例如,std::vector
或std::string
等标准容器类都有一个成员函数swap
,用于交换两个同类型容器的内容。
std::swap
函数
std::swap
是一个通用的函数模板,可以交换任意类型的两个变量。以下是使用 std::swap
的示例:
#include <iostream>
#include <utility> // std::swap
int main() {
int a = 5;
int b = 10;
std::cout << "Before swap: a = " << a << ", b = " << b << std::endl;
std