std::replace_copy() 算法
- 自 C++20 起
- 自 C++17 起
- C++17 之前
// (1)
template< class InputIt, class OutputIt, class T >
constexpr OutputIt replace_copy( InputIt first, InputIt last, OutputIt d_first,
const T& old_value, const T& new_value );
// (2)
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T >
ForwardIt2 replace_copy( ExecutionPolicy&& policy,
ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first,
const T& old_value, const T& new_value );
// (1)
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 );
// (2)
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T >
ForwardIt2 replace_copy( ExecutionPolicy&& policy,
ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first,
const T& old_value, const T& new_value );
// (1)
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 );
-
(1) 将范围 [
first
;last
) 中的元素复制到从d_first
开始的另一个范围,同时用new_value
替换等于old_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 | 目标范围的开头。 |
old_value | 要替换的元素的值。 |
new_value | 用作替换的值。 |
policy | 要使用的执行策略。有关详细信息,请参阅执行策略。 |
类型要求
InputIt | 旧式输入迭代器(LegacyInputIterator) |
OutputIt | 旧式输出迭代器(LegacyOutputIterator) |
ForwardIt1 ForwardIt2 | 旧式前向迭代器(LegacyForwardIterator) |
表达式 *first
和 new_value
的结果必须可写入 d_first
。
返回值
指向复制的最后一个元素之后元素的迭代器。
复杂度
给定 N
为 std::distance(first, last)
使用 operator==
与 old_value
进行恰好 N 次比较。
对于带有 ExecutionPolicy
的重载,如果 ForwardIt1
的 value_type
不是可移动构造(MoveConstructible)的,则可能会有性能开销。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数执行时抛出异常,并且
ExecutionPolicy
是标准策略之一,则会调用std::terminate
。对于任何其他ExecutionPolicy
,行为是实现定义的. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
可能的实现
replace_copy (1)
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;
}
示例
以下代码复制并打印一个向量,同时将所有大于 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