Defined in header <algorithm> | ||||
---|---|---|---|---|
| (1) | |||
| (2) |
Replaces all elements satisfying specific criteria with new_value
in the range [first, last)
. The first version replaces the elements that are equal to old_value
, the second version replaces elements for which predicate p
returns true
.
Parameters
first, last | - | the range of elements to process |
old_value | - | the value of elements to replace |
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:
The signature does not need to have |
new_value | - | the value to use as replacement |
Type requirements | ||
- ForwardIt must meet the requirements of ForwardIterator . | ||
- UnaryPredicate must meet the requirements of Predicate . |
Return value
(none).
Complexity
Exactly last - first
applications of the predicate.
Possible implementation
First version | ||
---|---|---|
| ||
Second version | ||
|
Example
The following code at first replaces all occurrences of 8
with 88
in a vector of integers. Then it replaces all values less than 5
with 55.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #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' ; } |
Output:
1 2 | 5 7 4 2 88 6 1 9 0 3 5 7 55 55 88 6 55 9 55 55 |
See also
copies a range, replacing elements satisfying specific criteria with another value (function template) | |
std::experimental::parallel::replace
(parallelism TS) | parallelized version of std::replace (function template) |
std::experimental::parallel::replace_if
(parallelism TS) | parallelized version of std::replace_if (function template) |
Please login to continue.