示例:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//常用查找和替换 replace_if
class Greate30
{
public:
bool operator()(int val)
{
return val >= 30;
}
};
class MyPrint
{
public:
void operator()(int val)
{
cout << val << " ";
}
};
void test01()
{
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(40);
v.push_back(30);
v.push_back(70);
v.push_back(20);
v.push_back(50);
v.push_back(30);
v.push_back(40);
v.push_back(10);
cout << "替换前:" << endl;
for_each(v.begin(), v.end(), MyPrint());
cout << endl;
cout << "替换后:" << endl;
//replace_if按条件查找
replace_if(v.begin(), v.end(), Greate30(), 4444);
for_each(v.begin(), v.end(), MyPrint());
cout << endl;
}
int main()
{
test01();
return 0;
}
总结:replace_if按条件查找,可以利用仿函数灵活筛选满足的条件