在线文档教程
C++
算法 | Algorithm

std::replace_if

STD::替换,STD::替换[医]如果

Defined in header
template< class ForwardIt, class T > void replace( ForwardIt first, ForwardIt last, const T& old_value, const T& new_value (1)
template< class ExecutionPolicy, class ForwardIt, class T > void replace( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, const T& old_value, const T& new_value (2)(since C++17)
template< class ForwardIt, class UnaryPredicate, class T > void replace_if( ForwardIt first, ForwardIt last, UnaryPredicate p, const T& new_value (3)
template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate, class T > void replace_if( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p, const T& new_value (4)(since C++17)

将满足特定条件的所有元素替换为new_value在范围内[first, last)...

1%29替换所有等于old_value...

3%29替换谓词的所有元素。p回报true...

2,4%29与%281,3%29相同,但根据policy这些过载不参与过载解决,除非std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>是真的

参数

first, last-the range of elements to process
old_value-the value of elements to replace
policy-the execution policy to use. See execution policy for details.
p-unary predicate which returns ​true if the element value should be replaced. The signature of the predicate function should be equivalent to the following: bool pred(const Type &a The signature does not need to have const &, but the function must not modify the objects passed to it. The type Type must be such that an object of type ForwardIt can be dereferenced and then implicitly converted to Type. ​
new_value-the value to use as replacement

类型要求

---。

-单数预测必须满足谓词的要求。

返回值

%280%29

复杂性

一点儿没错last - first谓词的应用。

例外

带有名为ExecutionPolicy报告错误如下:

  • 如果执行作为算法一部分调用的函数,则引发异常ExecutionPolicy是其中之一标准政策,,,std::terminate叫做。对于任何其他人ExecutionPolicy,行为是由实现定义的。

  • 如果算法不能分配内存,std::bad_alloc被扔了。

可能的实施

第一版

*。

模板<类向前,类T>替换%28 Forwardit First,Forwardit Lest,Const T&old[医]价值,康斯特T&新[医]值%29{表示%28;第一%21=最后;++第一%29{如果%28%2A第一=老[医]数值%29{%2AFirst=New[医]值;}}

第二版

模板<类向前,类单数预测,类T>空替换[医]如果%28先前进,最后前进,单数预测p,Const T&New[医]值%29{表示%28;第一%21=最后;++第一%29{如果%28 p%28%2A第1%29%29{%2AFirst=New[医]值;}}

下面的代码首先替换所有出现在8带着88在整数向量中。然后,它替换所有小于555岁。

二次

#include <algorithm> #include <array> #include <iostream> #include <functional> 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

二次

另见

replace_copyreplace_copy_ifcopies a range, replacing elements satisfying specific criteria with another value (function template)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/Algorithm/替换