#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
//copy 将容器指定范围内的元素拷贝到另一容器中
void vPrint(int num)
{
cout << num << " ";
}
void test01()
{
vector<int>v1 = { 0,1,2,3,4,5,6,7,8,9 };
vector<int>v2;
//提前开辟空间
v2.resize(v1.size());
//拷贝
copy(v1.begin(), v1.end(), v2.begin());
//打印
for_each(v2.begin(), v2.end(), vPrint);
cout << endl;
}
//replace 将指定范围内的旧元素修改成新元素
//replace(iterator beg,iterator end, oldvalue, newvalue)
void test02()
{
vector<int>v = { 0,1,5,7,6,6,6 };
cout << "修改前:" << endl;
for_each(v.begin(), v.end(), vPrint);
cout << endl;
//修改,将区间内的6改成2
replace(v.begin(), v.end(), 6, 2);
cout << "修改后:" << endl;
for_each(v.begin(), v.end(), vPrint);
cout << endl;
}
//replace_if 将指定范围内满足条件的元素替换成新元素
class Great3
{
public:
bool operator()(int num)
{
return num > 3;
}
};
void test03()
{
vector<int>v = { 0,1,2,3,4,5,6,7,8,9 };
cout << "修改前:" << endl;
for_each(v.begin(), v.end(), vPrint);
cout << endl;
//将区间内满足谓词条件的元素换成5
replace_if(v.begin(), v.end(), Great3(), 5);
cout << "修改后:" << endl;
for_each(v.begin(), v.end(), vPrint);
cout << endl;
}
//swap 互换两个容器元素
void test04()
{
vector<int>v1 = { 0,0,0,0,0 };
vector<int>v2 = { 1,1,1,1,1 };
cout << "替换前:v1:";
for_each(v1.begin(), v1.end(), vPrint);
cout << " v2:";
for_each(v2.begin(), v2.end(), vPrint);
cout << endl;
//互换
swap(v1, v2);
cout << "替换后:v1:";
for_each(v1.begin(), v1.end(), vPrint);
cout << " v2:";
for_each(v2.begin(), v2.end(), vPrint);
cout << endl;
}
int main()
{
test04();
system("pause");
return 0;
}
C++:STL-常用拷贝和替换算法
最新推荐文章于 2022-07-28 22:11:22 发布