std::replace_if() 算法
- 自 C++20 起
- 自 C++17 起
- C++17 之前
// (1)
template< class ForwardIt, class UnaryPredicate, class T >
constexpr void replace_if( ForwardIt first, ForwardIt last,
UnaryPredicate p, const T& new_value );
// (2)
template< class ExecutionPolicy, class ForwardIt,
class UnaryPredicate, class T >
void replace_if( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last,
UnaryPredicate p, const T& new_value );
// (1)
template< class ForwardIt, class UnaryPredicate, class T >
void replace_if( ForwardIt first, ForwardIt last,
UnaryPredicate p, const T& new_value );
// (2)
template< class ExecutionPolicy, class ForwardIt,
class UnaryPredicate, class T >
void replace_if( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last,
UnaryPredicate p, const T& new_value );
// (1)
template< class ForwardIt, class UnaryPredicate, class T >
void replace_if( ForwardIt first, ForwardIt last,
UnaryPredicate p, const T& new_value );
-
(1) 在范围 [
first
;last
) 中,将所有使得谓词p
返回true
的元素替换为new_value
。 -
(2) 与 (1) 相同,但根据
policy
执行。重载决议这些重载只有在
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
(C++20 前)std::is_execution_policy_v<std::replace_if_cvref_t<ExecutionPolicy>>
(C++20 起) 为true
时才参与重载决议。
参数
first last | 要处理的元素范围。 |
new_value | 用于替换的值。 |
policy | 要使用的执行策略。有关详细信息,请参阅执行策略。 |
p | 一元谓词,如果元素值应该被替换,则返回 对于类型为(可能是 const) |
类型要求
ForwardIt | LegacyForwardIterator |
一元谓词 | 谓词 |
- 自 C++20 起
- 直到 C++20
*first | 必须可写到 d_first 。 |
*first = new_value
必须有效。返回值
(无)
复杂度
给定 N
为 std::distance(first, last)
恰好 N 次谓词 p
的应用。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数在执行过程中抛出异常,且
ExecutionPolicy
是标准策略之一,则调用std::terminate
。对于任何其他ExecutionPolicy
,行为是实现定义的. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
可能的实现
replace_if (1)
template<class ForwardIt, class UnaryPredicate, class T>
void replace_if(ForwardIt first, ForwardIt last,
UnaryPredicate p, const T& new_value)
{
for (; first != last; ++first)
if (p(*first))
*first = new_value;
}
备注
由于算法通过引用获取 old_value
和 new_value
,如果其中任何一个引用范围 [first
; last
) 中的元素,可能会产生意外行为。
示例
以下代码首先将整数向量中所有出现的 8
替换为 88
。然后将所有小于 5
的值替换为 55
。
#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