std::replace() 算法
- 自 C++20 起
- 自 C++17 起
- C++17 之前
// (1)
template< class ForwardIt, class T >
constexpr void replace( ForwardIt first, ForwardIt last,
const T& old_value, const T& new_value );
// (2)
template< class ExecutionPolicy, class ForwardIt, class T >
void replace( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last,
const T& old_value, const T& new_value );
// (1)
template< class ForwardIt, class T >
void replace( ForwardIt first, ForwardIt last,
const T& old_value, const T& new_value );
// (2)
template< class ExecutionPolicy, class ForwardIt, class T >
void replace( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last,
const T& old_value, const T& new_value );
// (1)
template< class ForwardIt, class T >
void replace( ForwardIt first, ForwardIt last,
const T& old_value, const T& new_value );
-
(1) 在范围 [
first
;last
) 中,将所有等于old_value
的元素替换为new_value
。 -
(2) 与 (1) 相同,但根据
policy
执行。重载决议这些重载只有在
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
(直到 C++20)std::is_execution_policy_v<std::replace_cvref_t<ExecutionPolicy>>
(自 C++20 起) 为true
时才参与重载决议。
参数
first last | 要处理的元素范围。 |
old_value | 要搜索和替换的值。 |
new_value | 用作替换的值。 |
policy | 要使用的执行策略。有关详细信息,请参阅执行策略。 |
类型要求
ForwardIt | LegacyForwardIterator |
- 自 C++20 起
- 直到 C++20
*first | 必须可写到 d_first 。 |
*first = new_value
必须有效。返回值
(无)
复杂度
给定 N
为 std::distance(first, last)
最多使用 operator==
与 old_value
进行 N 次比较。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数执行抛出异常,并且
ExecutionPolicy
是标准策略之一,则调用std::terminate
。对于任何其他ExecutionPolicy
,行为是实现定义的. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
可能的实现
replace (1)
template<class ForwardIt, class T>
void replace(ForwardIt first, ForwardIt last,
const T& old_value, const T& new_value)
{
for (; first != last; ++first)
if (*first == old_value)
*first = new_value;
}
备注
由于算法通过引用接收 old_value
和 new_value
,如果其中任何一个是范围 [first
; last
) 中元素的引用,则可能导致意外行为。
示例
由于算法通过引用接收 old_value
和 new_value,如果其中任何一个是范围 [first
; last
) 中元素的引用,则可能导致意外行为。
#include <algorithm>
#include <array>
#include <functional>
#include <iostream>
int main()
{
std::array<int, 10> s {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
std::replace(s.begin(), s.end(), 8, 88);
for (int a : s)
std::cout << a << ' ';
std::cout << '\n';
std::replace_if(s.begin(), s.end(), std::bind(std::less<int>(), std::placeholders::_1, 5), 55);
for (int a : s)
std::cout << a << ' ';
std::cout << '\n';
}
5 7 4 2 88 6 1 9 0 3
5 7 55 55 88 6 55 9 55 55