Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::replace — replace values in place

std::replace from <algorithm> replaces every occurrence of a specified value within an iterator range. It modifies existing elements, preserves the container's size, and returns void.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <algorithm>

template<class ForwardIt, class T>
constexpr void replace(ForwardIt first, ForwardIt last,
                       const T& old_value, const T& new_value);

std::replace(first, last, old_value, new_value);

std::replace(first, last, old_value, new_value) from <algorithm> assigns new_value to each element for which *i == old_value is true. The range [first, last) includes first but excludes last. The algorithm changes values in place without removing or adding elements, and returns void, not a replacement count.

The shown overload without an execution policy requires a valid range of at least forward iterators and the ability to assign new_value through an iterator. An iterator to constant elements is insufficient. In C++23, both value arguments participate in deducing the same type T; use matching types. The algorithm performs exactly as many comparisons as there are elements in the range, giving O(N) complexity.

Do not pass old_value or new_value as a reference to an element the algorithm might change: changing that element can affect subsequent comparisons or assignments. Copy the value into a separate variable first if necessary. Use std::replace_if to select elements with a predicate, or std::replace_copy to write the result into another range.

The example replaces every 2 with 9. The supplied declaration targets C++23; the referenced online standard draft is updated over time and may contain later extensions.

Examples

#include <algorithm>
#include <array>
#include <cstddef>
#include <iostream>

int main() {
    std::array<int, 5> values{2, 1, 2, 3, 2};
    std::replace(values.begin(), values.end(), 2, 9);

    for (std::size_t i = 0; i < values.size(); ++i) {
        if (i != 0) {
            std::cout << ' ';
        }
        std::cout << values[i];
    }
    std::cout << '\n';
}

Result

9 1 9 3 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.

Sources