1、copy复制
1.1 将容器中指定范围的元素拷贝到另一容器中
1.2 目标容器要有容量
2、replace按值替换
2.1 将区间内指定的旧元素替换为新元素
3、replace_if 按条件替换
3.1 将区间中符合条件的旧元素替换为新元素
4、swap 交换
4.1 交换两个容器中的所有元素
5
#include"pch.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<iterator>//ostream_iterator
using namespace std;
//copy 将容器中指定范围的元素拷贝到另一容器中
void test01()
{
vector<int>v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
vector<int>vTarget;
vTarget.resize(v1.size());
copy(v1.begin(), v1.end(), vTarget.begin());
cout << "copy vTarget: " << endl;
/*for_each(vTarget.begin(), vTarget.end(), [](int val) {cout << val <<" "; });
cout << endl;*/
//利用输出流迭代器进行打印
copy(vTarget.begin(), vTarget.end(), ostream_iterator<int>(cout," "));
cout << endl;
}
//replace 将指定范围内旧元素修改为新元素
//replace_if 按条件进行替换
class MyCompare2
{
public:
bool operator()(int val)
{
return val > 3;
}
};
void test02()
{
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v2.push_back(i);
}
replace(v2.begin(), v2.end(), 3, 300);
cout << "after replace: " << endl;
copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " "));
cout << endl;
//按条件进行替换
//将所有大于3的替换为300
replace_if(v2.begin(), v2.end(), MyCompare2(), 3000);
cout << "after replace_if: " << endl;
copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " "));
}
//swap 互换两个容器元素
void test03()
{
vector<int>v3;
for (int i = 0; i < 10; i++)
{
v3.push_back(i);
}
vector<int>v4(10, 100);
cout << "before swap: " << endl;
cout << "v3= ";
copy(v3.begin(), v3.end(), ostream_iterator<int>(cout, " "));
cout << endl;
cout << "v4= ";
copy(v4.begin(), v4.end(), ostream_iterator<int>(cout, " "));
cout << endl;
swap(v3, v4);
cout << "after swap: " << endl;
cout << "v3= ";
copy(v3.begin(), v3.end(), ostream_iterator<int>(cout, " "));
cout << endl;
cout << "v4= ";
copy(v4.begin(), v4.end(), ostream_iterator<int>(cout, " "));
}
int main()
{
//test01();
//test02();
test03();
}
、测试程序