std::replace_copy, std::replace_copy_if
|
|
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
| 定义于头文件 <algorithm>
|
||
| template< class InputIt, class OutputIt, class T > OutputIt replace_copy( InputIt first, InputIt last, OutputIt d_first, |
(1) | |
| template< class InputIt, class OutputIt, class UnaryPredicate, class T > OutputIt replace_copy_if( InputIt first, InputIt last, OutputIt d_first, |
(2) | |
Copies the all elements from the range [first, last) to another range beginning at d_first replacing all elements satisfying specific criteria with new_value. The first version replaces the elements that are equal to old_value, the second version replaces elements for which predicate p returns true. The source and destination ranges cannot overlap.
目录 |
[编辑] 参数
| first, last | - | |
| d_first | - | |
| old_value | - | |
| p | - | 则返回 true 的一元谓词。 谓词函数签名应等价于如下者: bool pred(const Type &a); 签名不必拥有 const & ,但函数必须不修改传递给它的对象。 |
| new_value | - | |
| 类型要求 | ||
-InputIt 必须满足 InputIterator 的要求。
| ||
-OutputIt 必须满足 OutputIterator 的要求。
| ||
[编辑] 返回值
[编辑] 复杂度
last - first的谓词中的应用.[编辑] 可能的实现
| 版本一 |
|---|
template<class InputIt, class OutputIt, class T> OutputIt replace_copy(InputIt first, InputIt last, OutputIt d_first, const T& old_value, const T& new_value) { for (; first != last; ++first) { *d_first++ = (*first == old_value) ? new_value : *first; } return d_first; } |
| 版本二 |
template<class InputIt, class OutputIt, class UnaryPredicate, class T> OutputIt replace_copy_if(InputIt first, InputIt last, OutputIt d_first, UnaryPredicate p, const T& new_value) { for (; first != last; ++first) { *d_first++ = (p( *first ) ? new_value : *first; } return d_first; } |
[编辑] 示例
The following copy prints a vector, replacing all values over 5 with 99 on the fly.
#include <algorithm> #include <vector> #include <iostream> #include <iterator> #include <functional> int main() { std::vector<int> v{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; std::replace_copy_if(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "), [](int n){return n > 5;}, 99); std::cout << '\n'; }
输出:
5 99 4 2 99 99 1 99 0 3
[编辑] 另请参阅
| 删除满足特定条件的元素 (函数模板) |