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 | - | 的目标范围的开头
原文: the beginning of the destination range |
old_value | - | 的值的元素来代替
|
p | - | unary predicate which returns true 如果元素的值应进行更换 . 原文: if the element value should be replaced The signature of the predicate function should be equivalent to the following: bool pred(const Type &a); The signature does not need to have const &, but the function must not modify the objects passed to it. |
new_value | - | 要使用的值作为替代品
|
类型要求 | ||
-InputIt 必须满足 InputIterator 的要求。
| ||
-OutputIt 必须满足 OutputIterator 的要求。
|
[编辑] 返回值
[编辑] 复杂度
last - first
的谓词中的应用.last - first
applications of the predicate.[编辑] 可能的实现
版本一 |
---|
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
[编辑] 另请参阅
删除满足特定条件的元素 (函数模板) |