无涯教程-C++ 向量 - swap()函数

78 阅读1分钟

此函数用于交换两个向量中指定的元素。

swap - 语法

考虑两个向量v1和v2。语法为:

v1.swap(v2);

swap - 范围

v2  -  v2是一个向量,其值将与另一个向量交换。

swap - 返回值

它不返回任何值。

swap - 例子1

让我们看一个简单的例子。

#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<<
;
cout<<"Before swapping,elements of v2 are :";
for(int i=0;i<v2.size();i++)
cout<<v2[i]<<" ";
cout<<
;
v1.swap(v2);
cout<<"After swapping,elements of v1 are  :";
for(int i=0;i<v1.size();i++)
cout<<v1[i]<<" ";
cout<<
;
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交换。

参考链接

www.learnfk.com/c++/cpp-vec…