功能描述:
- 将空间内满足条件的元素替换成指定元素
函数原型:
- replace_if(iterator beg, iterator end, _Pred, newvalue);
//按条件替换元素,满足条件的替换成指定元素
//beg 开始迭代器
//end 结束迭代器
//_Pred谓词
//newvalue 替换的新元素
#include<iostream>#include<algorithm>#include<vector>using namespace std;//常用拷贝和替换算法 replace_ifclass myprint {public:void operator()(int val) {cout << val << " ";}};class Greater30 {public:bool operator()(int val) {return val >= 30;}};void test01() {vector<int> v;v.push_back(10);v.push_back(20);v.push_back(30);v.push_back(20);v.push_back(40);v.push_back(10);v.push_back(20);cout << "替换前:" << endl;for_each(v.begin(), v.end(),myprint());cout << endl;//将大于等于30的元素替换为15replace_if(v.begin(), v.end(), Greater30(), 15);cout << "替换后:" << endl;for_each(v.begin(), v.end(), myprint());cout << endl;}int main() {test01();return 0;}
运行结果:
