Namespaces
Variants

std::replace, std::replace_if

来自 zh.cppreference.net
 
 
算法库
受约束算法和范围算法 (C++20)
受约束算法,例如 ranges::copy 、 ranges::sort 、 ...
排序及相关操作
划分操作
(C++11)    

排序操作
二分搜索操作
(在已划分范围上)
集合操作(在已排序范围上)
合并操作(在已排序范围上)
堆操作
最小/最大操作
(C++11)
(C++17)
字典序比较操作
排列操作


 
定义于头文件 <algorithm>
template< class ForwardIt, class T >
void replace( ForwardIt first, ForwardIt last,
              const T& old_value, const T& new_value );
(1) (直至 C++26)
(自 C++20 起为 constexpr)
template< class ForwardIt, class T = typename std::iterator_traits
                                         <ForwardIt>::value_type >
constexpr void replace( ForwardIt first, ForwardIt last,
                        const T& old_value, const T& new_value );
(自 C++26 起)
template< class ExecutionPolicy, class ForwardIt, class T >
void replace( ExecutionPolicy&& policy,
              ForwardIt first, ForwardIt last,
              const T& old_value, const T& new_value );
(2) (自 C++17 起)
(直至 C++26)
template< class ExecutionPolicy, class ForwardIt,
          class T = typename std::iterator_traits
                        <ForwardIt>::value_type >
void replace( ExecutionPolicy&& policy,
              ForwardIt first, ForwardIt last,
              const T& old_value, const T& new_value );
(自 C++26 起)
template< class ForwardIt, class UnaryPred, class T >
void replace_if( ForwardIt first, ForwardIt last,
                 UnaryPred p, const T& new_value );
(3) (直至 C++26)
(自 C++20 起为 constexpr)
template< class ForwardIt, class UnaryPred,
          class T = typename std::iterator_traits
                        <ForwardIt>::value_type> >
constexpr void replace_if( ForwardIt first, ForwardIt last,
                           UnaryPred p, const T& new_value );
(自 C++26 起)
template< class ExecutionPolicy,
          class ForwardIt, class UnaryPred, class T >
void replace_if( ExecutionPolicy&& policy,
                 ForwardIt first, ForwardIt last,
                 UnaryPred p, const T& new_value );
(4) (自 C++17 起)
(直至 C++26)
template< class ExecutionPolicy,
          class ForwardIt, class UnaryPred,
          class T = typename std::iterator_traits
                        <ForwardIt>::value_type> >
void replace_if( ExecutionPolicy&& policy,
                 ForwardIt first, ForwardIt last,
                 UnaryPred p, const T& new_value );
(自 C++26 起)

如果满足特定条件,则将范围 [first, last) 中的所有元素替换为 new_value 。

1) 将所有等于 old_value 的元素替换(使用 operator== )。
3) 将所有谓词 p 返回 true 的元素替换。
2,4) 同 (1,3) ,但按 policy 执行。
仅在下列表达式的值为 true 时,这些重载才会参与重载决议:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(直至 C++20)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(自 C++20 起)

如果 *first = new_value 无效(直至 C++20)new_value不可写入到 first(自 C++20 起),则程序非良构。

参数

first, last - 定义待处理元素范围的迭代器对
old_value - 待替换的元素值
policy - 使用的执行策略
p - 一元谓词,当元素值应被替换时返回​ true 。

表达式 p ( v ) 必须可转换为 bool ,其中 v 是类型为 VT (可能为 const 限定)的实参, VT 是 ForwardIt 的值类型,且与值类别无关,同时不得修改 v 。因此,不允许使用 VT & 作为参数类型 ,也不允许使用 VT ,除非对于 VT 类型移动操作等价于拷贝操作 (since C++11) 。 ​

new_value - 用作替换的值
类型要求
-
ForwardIt 必须满足 LegacyForwardIterator 的要求。
-
UnaryPred 必须满足 Predicate 的要求。

复杂度

给定 N 为 std:: distance ( first, last ) :

1,2) 使用 operator == 进行恰好 N 次比较。
3,4) 恰好应用谓词 p N 次。

异常

带有名为 ExecutionPolicy 模板参数的重载按以下方式报告错误:

  • 如果作为算法一部分调用的函数执行抛出异常,且 ExecutionPolicy 是某个 标准策略 ,则调用 std::terminate 。对于其他任何 ExecutionPolicy ,其行为由实现定义。
  • 如果算法无法分配内存,则抛出 std::bad_alloc 。

注释

由于该算法通过引用接收 old_value 和 new_value ,若其中任一参数是区间 [ first , last ) 中元素的引用,则可能导致未预期行为。

功能测试 宏 值 标准 功能
__cpp_lib_algorithm_default_value_type 202403 (C++26) 列表初始化 用于算法 ( 1-4 )

可能实现

replace (1)
template<class ForwardIt,
         class T = typename std::iterator_traits<ForwardIt>::value_type>
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;
}
replace_if (3)
template<class ForwardIt, class UnaryPred,
         class T = typename std::iterator_traits<ForwardIt>::value_type>
void replace_if(ForwardIt first, ForwardIt last,
                UnaryPred p, const T& new_value)
{
    for (; first != last; ++first)
        if (p(*first))
            *first = new_value;
}
(注:根据要求,HTML标签、属性及 标签内的C++代码均未翻译,仅翻译了可见的文本描述部分。由于原文中除代码外无其他需要翻译的文本内容,故保持原样输出)

示例

#include <algorithm>
#include <array>
#include <complex>
#include <functional>
#include <iostream>
void println(const auto& seq)
{
    for (const auto& e : seq)
        std::cout << e << ' ';
    std::cout << '\n';
}
int main()
{
    std::array<int, 10> s{5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
    // 将所有出现的8替换为88
    std::replace(s.begin(), s.end(), 8, 88);
    println(s);
    // 将所有小于5的值替换为55
    std::replace_if(s.begin(), s.end(), 
                    std::bind(std::less<int>(), std::placeholders::_1, 5), 55);
    println(s);
    std::array<std::complex<double>, 2> nums{{{1, 3}, {1, 3}}};
    #ifdef __cpp_lib_algorithm_default_value_type
        std::replace(nums.begin(), nums.end(), {1, 3}, {4, 2});
    #else
        std::replace(nums.begin(), nums.end(), std::complex<double>{1, 3},
                                               std::complex<double>{4, 2});
    #endif
    println(nums);
}

输出:

5 7 4 2 88 6 1 9 0 3
5 7 55 55 88 6 55 9 55 55
(4,2), (4,2)

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 应用于 发布时行为 正确行为
LWG 283 C++98 要求 T 必须是 可复制赋值 (且对于 replace
需为 可相等比较 ),但 ForwardIt 的值类型并非
总是 T ,且 T 并非总是可写入 ForwardIt
改为要求 * first = new_value
必须合法有效

参见

复制范围,将满足特定条件的元素替换为另一个值
(函数模板 & 算法函数对象)
将所有满足特定条件的值替换为另一个值
(算法函数对象)