一、算法简介
1、copy //容器内指定范围的元素拷贝到另一容器中
2、replace //将容器内指定范围的就元素改为新元素
3、replace_if //容器内指定范围满足条件的元素替换为新元素
4、swap //互换两个容器的元素
二、copy
1、函数原型
copy(itreator beg,iterator end,iterator dest); //按值查找元素,找到返回指定位置迭代器
2、示例
代码如下(示例):
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void myPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v1;
for (int i = 0; i > 10; i++)
{
v1.push_back(i);
}
vector<int>v2;
v2.resize(v1.size());
copy(v1.begin(), v1.end(),v2.begin());
for_each(v2.begin(), v2.end(),myPrint);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
三、replace
1、函数原型
replace(iterator beg,iterator end,oldvalue,newvalue); //将区间内旧元素 替换成 新元素 oldvalue旧元素 newvalue新元素
2、示例
代码如下(示例):
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void myPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(10);
v.push_back(50);
cout << "替换前:" << endl;
for_each(v.begin(), v.end(), myPrint);
cout << endl;
cout << "替换后:" << endl;
//将10替换100
replace(v.begin(), v.end(), 10, 100);
for_each(v.begin(), v.end(), myPrint);
}
int main()
{
test01();
system("pause");
return 0;
}
四、replace_if
1、函数原型
replace_if(iterator beg,iterator end,_Pred,newvalue); //按条件替换元素,满足条件的替换成指定元素,_Pred谓词,newvalue替换的新元素
2、示例
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void myPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(10);
v.push_back(50);
cout << "替换前:" << endl;
for_each(v.begin(), v.end(), myPrint);
cout << endl;
cout << "替换后:" << endl;
//将10替换100
replace(v.begin(), v.end(), 10, 100);
for_each(v.begin(), v.end(), myPrint);
}
int main()
{
test01();
system("pause");
return 0;
}
五、swap
1、函数原型
swap(container c1,container c2); //互换两个容器元素