本文内容来自C++Plus,本文只是本人的总结和翻译而已。本人只是C++的搬运工。
原文传送门:http://www.cplusplus.com/reference/algorithm/replace_copy/
replace_copy算法:copy一段区间,并且对选定值进行替换
template <class InputIterator, class OutputIterator, class T>
OutputIterator replace_copy (InputIterator first, InputIterator last,
OutputIterator result, const T& old_value, const T& new_value)
{
while (first!=last) {
*result = (*first==old_value)? new_value: *first;
++first; ++result;
}
return result;
}
将一段区间copy到指定位置,在拷贝的过程中就对选定的值进行替换。
下面是测试代码:
// replace_copy example
#include <iostream> // std::cout
#include <algorithm> // std::replace_copy
#include <vector> // std::vector
int main () {
int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
std::vector<int> myvector (8);
std::replace_copy (myints, myints+8, myvector.begin(), 20, 99);
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}