std::replace_copy_if() 算法
- 自 C++20 起
- 自 C++17 起
- C++17 之前
// (1)
template< class InputIt, class OutputIt, class UnaryPredicate, class T >
constexpr OutputIt replace_copy_if( InputIt first, InputIt last, OutputIt d_first,
UnaryPredicate p, const T& new_value );
// (2)
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2,
class UnaryPredicate, class T >
ForwardIt2 replace_copy_if( ExecutionPolicy&& policy,
ForwardIt1 first, ForwardIt1 last,
ForwardIt2 d_first,
UnaryPredicate p, const T& new_value );
// (1)
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 );
// (2)
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2,
class UnaryPredicate, class T >
ForwardIt2 replace_copy_if( ExecutionPolicy&& policy,
ForwardIt1 first, ForwardIt1 last,
ForwardIt2 d_first,
UnaryPredicate p, const T& new_value );
// (1)
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 );
-
(1) 将范围 [
first
;last
) 中的元素复制到从d_first
开始的另一个范围,同时将满足谓词p
的元素替换为new_value
(使用operator==
进行比较)。 -
(2) 与 (1) 相同,但根据
policy
执行。重载决议这些重载只有在
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
(C++20 之前)std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>
(C++20 起) 为true
时才参与重载决议。
参数
first last | 要复制的元素范围。 |
d_first | 目标范围的开头。 |
policy | 要使用的执行策略。有关详细信息,请参阅执行策略。 |
p | 一元谓词,如果元素应被替换则返回 对于类型为(可能是 const) |
类型要求
InputIt | LegacyInputIterator |
OutputIt | LegacyOutputIterator |
ForwardIt1 ForwardIt2 | LegacyForwardIterator |
Predicate | 一元谓词 |
表达式 *first
和 new_value
的结果必须可写入 d_first
。
返回值
指向复制的最后一个元素之后元素的迭代器。
复杂度
给定 N
为 std::distance(first, last)
谓词 p
的应用次数恰好为 N。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数执行时抛出异常且
ExecutionPolicy
是标准策略之一,则调用std::terminate
。对于任何其他ExecutionPolicy
,行为是实现定义的. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
可能的实现
replace_copy_if (1)
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;
}
示例
以下代码复制并打印一个向量,同时将所有大于 5
的值替换为 99
。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
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