C++算法 replace()函数用于用[first,last)参数内的new_value值替换所有等于old_value的值。
此函数检查参数内的每个元素,如果与指定值匹配,则将其替换。
template <class ForwardIterator, class T> void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value);
first:一个正向迭代器,它指向要替换元素的参数内的初始位置。
last:一个正向迭代器,指向要替换元素的参数内的最终位置。
old_value :要替换的元素的旧值。
new_value :将新值分配给具有旧值的元素。
没有
让我们看一个简单的示例来演示replace()的用法:
#include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { vector<int> v = { 3,1,2,1,2 }; replace(v.begin(), v.end(), 1, 10); for_each(v.begin(), v.end(), [](int x) { cout << x << ","; }); return 0; }
输出:
3,10,2,10,2,
在上面的示例中,向量v的元素1被替换为10。
让我们看另一个简单的例子:
#include <vector> #include <algorithm> #include <iostream> int main( ) { using namespace std; vector <int> v1; vector <int>::iterator Iter1; int i; for ( i = 0 ; i <= 9 ; i++ ) v1.push_back( i ); int ii; for ( ii = 0 ; ii <= 3 ; ii++ ) v1.push_back( 7 ); random_shuffle (v1.begin( ), v1.end( ) ); cout << "The original vector v1 is:\n ( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")." << endl; //Replace elements with a value of 7 with a value of 700 replace (v1.begin( ), v1.end( ), 7 , 700); cout << "The vector v1 with a value 700 replacing that of 7 is:\n ( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")." << endl; return 0; }
输出:
The original vector v1 is: ( 4 7 7 7 0 5 7 1 6 9 3 7 8 2 ). The vector v1 with a value 700 replacing that of 7 is: ( 4 700 700 700 0 5 700 1 6 9 3 700 8 2 ).
在上面的示例中,replace()从向量v1中找到所有与7匹配的元素,并将其替换为700。
让我们看另一个简单的例子:
#include <iostream> #include <vector> #include <algorithm> using namespace std; void print(vector<int>& v) { for(int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << endl; } int main() { vector<int> v = {1, 4, 3, 2, 3, 10, 7, 9, 3, 8}; cout << "v : "; print(v); //replace 3 with 6 replace(v.begin(), v.end(), 3, 6); cout << "After replacing 3 with 6\n"; cout << "v : "; print(v); return 0; }
输出:
v : 1 4 3 2 3 10 7 9 3 8 After replacing 3 with 6 v : 1 4 6 2 6 10 7 9 6 8
让我们看另一个简单的例子:
#include <iostream> //cout #include <algorithm> //replace #include <vector> //vector using namespace std; int main () { int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 }; vector<int> myvector (myints, myints+8); //10 20 30 30 20 10 10 20 replace (myvector.begin(), myvector.end(), 20, 99);//10 99 30 30 99 10 10 99 cout << "myvector contains:"; for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) cout << ' ' << *it; cout << '\n'; return 0; }
输出:
myvector contains: 10 99 30 30 99 10 10 99
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)