#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//所有区间满足条件的元素,替换成指定元素
//replace_if(iterator begin, iterator end, _Pred, newValue);
class MyReplace
{
public:
bool operator()(int val)
{
return val > 5;//大于5的被替换
}
};
void PrintVector(int val)
{
cout << val << " ";
}
void test1501()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
v.push_back(0);
cout << "替换前:" << endl;
for_each(v.begin(), v.end(), PrintVector);
cout << endl;
replace_if(v.begin(), v.end(), MyReplace(), 10);//迭代器遍历的数据传入仿函数中满足条件进行替换操作
cout << "替换后:" << endl;
for_each(v.begin(), v.end(), PrintVector);
cout << endl;
}
int main()
{
test1501();
system("pause");
return 0;
}
网友评论