此函数用于交换两个向量中指定的元素。
考虑两个向量v1和v2。语法为:
v1.swap(v2);
v2 - v2是一个向量,其值将与另一个向量交换。
它不返回任何值。
让我们看一个简单的例子。
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-vector-swap-function.html
来源:LearnFk无涯教程网
#include<iostream> #include<vector> using namespace std; int main() { vector<int> v1={1,2,3,4,5}; vector<int> v2={6,7,8,9,10}; cout<<"Before swapping,elements of v1 are :"; for (int i=0;i<v1.size();i++) cout<<v1[i]<<" "; cout<<'\n'; cout<<"Before swapping,elements of v2 are :"; for(int i=0;i<v2.size();i++) cout<<v2[i]<<" "; cout<<'\n'; v1.swap(v2); cout<<"After swapping,elements of v1 are :"; for(int i=0;i<v1.size();i++) cout<<v1[i]<<" "; cout<<'\n'; cout<<"After swapping,elements of v2 are:"; for(int i=0;i<v2.size();i++) cout<<v2[i]<<" "; return 0; }
输出:
Before swapping,elements of v1 are :1 2 3 4 5 Before swapping,elements of v2 are :6 7 8 9 10 After swapping,elements of v1 are :6 7 8 9 10 After swapping,elements of v2 are :1 2 3 4 5
在此示例中,swap()函数将向量v1的元素与向量v2交换。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)