CKTIS / C++
std::replace_if — replace elements matching a condition
std::replace_if from <algorithm> replaces elements satisfying a predicate in place with one supplied value. It preserves the number of elements and returns void.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <algorithm>
std::replace_if(first, last, pred, new_value); // returns voidstd::replace_if(first, last, pred, new_value) operates on the half-open range [first, last): it includes first but excludes last. When pred(*i) is true, it assigns new_value to that element. Other elements remain unchanged; the algorithm neither removes elements nor changes the container's size.
It requires mutable iterators of at least the forward category and the ability to assign new_value through an iterator. The predicate must produce a Boolean-testable result and must not modify the element being tested. For a range of length N, the predicate is called exactly N times, giving linear complexity. The result is void, not a replacement count.
The example replaces negative numbers with 0. Unlike std::replace, the condition comes from a predicate rather than comparison with one old value. If you need a separate output range, consider std::replace_copy_if. If new_value refers to an element in the range that satisfies the predicate, the algorithm assigns that element to itself. For int, as used in the example, self-assignment leaves the value unchanged. To avoid depending on how the element type handles self-assignment, pass a separate copy of the replacement value.
The overload shown has no execution policy and is suitable for C++23. The supplied sources are a living standard draft and may contain later extensions.
Examples
#include <algorithm>
#include <array>
#include <cstddef>
#include <iostream>
int main() {
std::array<int, 5> values{4, -2, 0, -7, 9};
std::replace_if(values.begin(), values.end(),
[](int x) { return x < 0; }, 0);
for (std::size_t i = 0; i < values.size(); ++i) {
if (i != 0) std::cout << ' ';
std::cout << values[i];
}
std::cout << '\n';
}
Result
4 0 0 0 9
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.