功能描述:
将区间内满足条件的元素,替换成指定元素
函数原型:
replace_if(iterator beg,iterator end,_Pred,newvalue);
//按条件替换区间内的满足条件的元素
//beg 开始迭代器
//end 结束迭代器
//_Pred 谓词
//newvalue 替换的新元素
#include <iostream>
using namespace std;
#include<vector>
#include<algorithm>
class Greater
{
public:
int operator()(int val)
{
return val > 4;
}
};
void MyPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
v.push_back(1);
v.push_back(2);
v.push_back(5);
v.push_back(4);
v.push_back(2);
v.push_back(3);
v.push_back(6);
cout << "替换前:" << endl;
for_each(v.begin(), v.end(), MyPrint);
cout << endl;
replace_if(v.begin(), v.end(), Greater(), 0);
cout << "替换后:" << endl;
for_each(v.begin(), v.end(), MyPrint);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
输出结果:
替换前:
1 2 5 4 2 3 6
替换后:
1 2 0 4 2 3 0
总结:replace_if按条件查找,可以利用仿函数灵活筛选满足的条件