vector :: swap()函数以及C ++ STL中的示例
C++vector::swap()函数
vector::swap()是“vector”头文件的库函数,用于交换向量的内容,用向量调用,并接受另一个向量作为参数并交换其内容。(两个向量的大小可能不同)。
注意:要使用向量,请包含<vector>标头。
vector::swap()函数的语法
vector::swap(vector& v);
参数:v–这是另一个要与当前向量交换内容的向量。
返回值:void–不返回任何内容。
示例
Input:
vector<int> v1{ 10, 20, 30, 40, 50 };
vector<int> v2{ 100, 200, 300 };
//交换向量的内容
v1.swap(v2);
Output:
//如果我们打印值
v1: 100 200 300
v2: 10 20 30 40 50C++程序演示vector::swap()函数的示例
//C++STL程序演示示例
//vector::erase()函数
#include <iostream>
#include <vector>
using namespace std;
int main(){
//向量声明
vector<int> v1{ 10, 20, 30, 40, 50 };
vector<int> v2{ 100, 200, 300 };
//打印向量的大小和值
cout << "before swap() call..." << endl;
cout << "size of v1: " << v1.size() << endl;
cout << "size of v2: " << v2.size() << endl;
cout << "v1: ";
for (int x : v1)
cout << x << " ";
cout << endl;
cout << "v2: ";
for (int x : v2)
cout << x << " ";
cout << endl;
//交换向量的内容
v1.swap(v2);
//打印向量的大小和值
cout << "after swap() call..." << endl;
cout << "size of v1: " << v1.size() << endl;
cout << "size of v2: " << v2.size() << endl;
cout << "v1: ";
for (int x : v1)
cout << x << " ";
cout << endl;
cout << "v2: ";
for (int x : v2)
cout << x << " ";
cout << endl;
return 0;
}输出结果
before swap() call... size of v1: 5 size of v2: 3 v1: 10 20 30 40 50 v2: 100 200 300 after swap() call... size of v1: 3 size of v2: 5 v1: 100 200 300 v2: 10 20 30 40 50
参考:C++vector::swap()