功能描述:
互换两个容器的元素
函数原理:
swap(container c1,container c2);
//互换两个容器的元素
//c1容器1
//c2容器2
#include <iostream>
using namespace std;
#include<vector>
#include<algorithm>
void MyPrint(vector<int>&v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
std::cout << *it << " ";
}
std::cout << endl;
}
void test01()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 100);
}
std::cout << "互换前:" << endl;
MyPrint(v1);
MyPrint(v2);
swap(v1,v2);//也可以写成v1.swap(v2);
std::cout << "互换后:" << endl;
MyPrint(v1);
MyPrint(v2);
}
int main()
{
test01();
system("pause");
return 0;
}
输出结果:
互换前:
0 1 2 3 4 5 6 7 8 9
100 101 102 103 104 105 106 107 108 109
互换后:
100 101 102 103 104 105 106 107 108 109
0 1 2 3 4 5 6 7 8 9
总结:swap交换容器时,注意交换的容器要同种类型