1.功能:将容器指定范围内的旧元素替换为新元素
2.函数原型
- replace(iterator beg, iterator end, oldvalue, newvalue)
- beg,end 开始和结束迭代器
- oldvalue,newvalue 旧元素,新元素
#include<iostream> #include<vector> #include<algorithm> #include<ctime> using namespace std; class myprint { public: void operator()(int val) { cout << val << " "; } }; void test1() { vector<int> v; v.push_back(2); v.push_back(8); v.push_back(6); v.push_back(5); v.push_back(4); v.push_back(2); v.push_back(2); cout << "替换前:" << endl; for_each(v.begin(), v.end(), myprint()); //遍历容器v 2 8 6 5 4 2 2 cout << endl; cout << "替换后:" << endl; replace(v.begin(), v.end(), 2, 222); //将所有的2代换为222 for_each(v.begin(), v.end(), myprint()); //遍历容器v 222 8 6 5 4 222 222 cout << endl; } int main() { test1(); return 0; }