C++ Vector 库 - swap() 函数
描述
C++ 函数 std::vector::swap() 交换两个向量的内容。
声明
以下是 std::vector::swap() 函数形式 std::vector 头的声明。
template <class T, class Alloc> void swap (vector<T,Alloc>& v1, vector<T,Alloc>& v2);
参数
v1 − 第一个向量容器。
v2 − 第二个向量容器。
返回值
None.
异常
此函数从不抛出异常。
时间复杂度
Linear i.e. O(1)
示例
以下示例显示了 std::vector::swap() 函数的用法。
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2 = {10, 20, 30};
cout << "Contents of vector v1 before swap operation" << endl;
for (int i = 0; i < v1.size(); ++i)
cout << v1[i] << endl;
cout << "Contents of vector v2 before swap operation" << endl;
for (int i = 0; i < v2.size(); ++i)
cout << v2[i] << endl;
swap(v1, v2);
cout << "Contents of vector v1 after swap operation" << endl;
for (int i = 0; i < v1.size(); ++i)
cout << v1[i] << endl;
cout << "Contents of vector v2 after swap operation" << endl;
for (int i = 0; i < v2.size(); ++i)
cout << v2[i] << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Contents of vector v1 before swap operation 1 2 3 4 5 Contents of vector v2 befor swap operation 10 20 30 Contents of vector v1 after swap operation 10 20 30 Contents of vector v2 after swap operation 1 2 3 4 5

