C++常用拷贝和替换算法-replace()
功能描述:
- 将容器内指定范围的旧元素修改为新元素
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class myPrint
{
public:
void operator()(int val)
{
cout << val << " ";
}
};
void test10()
{
vector<int> v;
v.push_back(20);
v.push_back(30);
v.push_back(20);
v.push_back(40);
v.push_back(50);
v.push_back(10);
v.push_back(20);
cout << "替换前: " << endl;
for_each(v.begin(), v.end(), myPrint());
cout << endl;
//将容器中的20替换成2000
cout << "替换后: " << endl;
replace(v.begin(), v.end(), 20, 2000);
for_each(v.begin(), v.end(), myPrint());
cout << endl;
}
int main()
{
test10();
return 0;
}
//replace会替换区间内满足条件的元素
C++常用拷贝和替换算法-replace()