replace()函数是算法标头的库函数,用于在容器的给定范围内用新值替换旧值,它接受指向开始和结束位置的迭代器,要替换的旧值以及要分配的新值。
注意:要使用replace()函数–包括<algorithm>头文件,或者您可以简单地使用<bits / stdc ++。h>头文件。
std :: replace()函数的语法
std::replace( iterator start, iterator end, const T& old_value, const T& new_value);
参数:
迭代器开始,迭代器结束–这些迭代器指向容器中我们必须运行替换操作的开始和结束位置。
old_value –是要搜索并替换为新值的值。
new_value –要分配的值,而不是old_value。
返回值: void –返回注释。
示例
Input:
vector<int> v{ 10, 20, 10, 20, 10, 30, 40, 50, 60, 70 };
//用99代替10-
replace(v.begin(), v.end(), 10, 99);
Output:
99 20 99 20 99 30 40 50 60 70在此程序中,我们有一个向量,并且正在将新值分配给旧值。
//C ++ STL程序演示使用
//std :: replace()函数
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
//向量
vector<int> v{ 10, 20, 10, 20, 10, 30, 40, 50, 60, 70 };
//打印矢量元素
cout << "before replacing, v: ";
for (int x : v)
cout << x << " ";
cout << endl;
//用99代替10-
replace(v.begin(), v.end(), 10, 99);
//打印矢量元素
cout << "after replacing, v: ";
for (int x : v)
cout << x << " ";
cout << endl;
return 0;
}输出结果
before replacing, v: 10 20 10 20 10 30 40 50 60 70 after replacing, v: 99 20 99 20 99 30 40 50 60 70
参考:C ++ std :: replace()