STL 中可以在序列中有选择地替换元素的最后一个算法是 replace_copy_if_if(),它和 replace_if() 算法是相同的,但它的结果会被保存到另一个序列中。
它的前两个参数是输入序列的迭代器,第 3 个参数是输出序列的开始迭代器,最后两个参数分别是谓词和替换值。
#include <algorithm>
template<class InputIterator, class OutputIterator, class Predicate, class Type>
OutputIterator replace_copy_if_if(
InputIterator _First,
InputIterator _Last,
OutputIterator _Result,
Predicate _Pred,
const Type& _Val
);
参数 | 描述 |
---|---|
_First | 输入迭代器 |
_Last | 输入迭代器 |
_Result | 输出迭代器 |
_Pred | 比较规则 |
_Val | 新值 |
使用 STL replace_copy_if 函数替换元素
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool isEVEN(int x)
{
if (x % 2 == 0)
return 1;
else
return 0;
}
int main ()
{
std::cout << "嗨客网(www.haicoder.net)\n" << std::endl;
int arr[] = { 10, 11, 12, 13, 14, 15, 100, 200, 300 };
vector<int> v(6);
cout << "before replacing, Array (arr): ";
for (int x : arr)
cout << x << " ";
cout << endl;
cout << "vector (v): ";
for (int x : v)
cout << x << " ";
cout << endl;
replace_copy_if(arr + 0, arr + 6, v.begin(), isEVEN, -1);
cout << "after replacing, Array (arr): ";
for (int x : arr)
cout << x << " ";
cout << endl;
cout << "vector (v): ";
for (int x : v)
cout << x << " ";
cout << endl;
return 0;
}
我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ replace_copy_if.cpp -std=c++11
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们使用了 replace_copy_if 函数,实现了替换了 vector 中的元素。
STL 中可以在序列中有选择地替换元素的最后一个算法是 replace_copy_if_if(),它和 replace_if() 算法是相同的,但它的结果会被保存到另一个序列中。
它的前两个参数是输入序列的迭代器,第 3 个参数是输出序列的开始迭代器,最后两个参数分别是谓词和替换值。