Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::inserter — insertion through an output iterator

std::inserter creates an output iterator that calls the container's insert on each assignment. This lets an algorithm such as std::copy add elements at a chosen position instead of overwriting existing ones.

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

Syntax

#include <iterator>

template<class Container>
constexpr std::insert_iterator<Container>
inserter(Container& x, std::ranges::iterator_t<Container> i);

// Usage:
// auto out = std::inserter(container, position);

std::inserter(x, i) from <iterator> returns a std::insert_iterator<Container>. Constructing the adaptor inserts nothing; writing through it calls the container's insert. The container must support that operation, and i must be a valid insertion position in x.

Assignment performs the equivalent of iter = container->insert(iter, value); ++iter;; for an rvalue argument, it uses std::move(value). The adaptor stores the iterator returned by insert and then increments it. If insert adds a new element, the stored position is immediately after that element. In a unique-key container such as std::set, if an equivalent key already exists, insert adds nothing and returns an iterator to the existing element. The stored position is then immediately after that existing element. In a sequence container, successive writes preserve input order. The adaptor's own operator++ does not advance the position: assignment does that.

The adaptor calls an insertion operation instead of overwriting an existing element. std::back_inserter uses push_back, and std::front_inserter uses push_front; std::inserter uses positional insert. The container must outlive use of the adaptor; independent modifications must not invalidate its stored position.

The example inserts 2 and 3 before 4, producing 1 2 3 4. The verification profile is C++23; the cited document is a rolling standard draft, not a frozen C++23 edition. This does not attest compiler availability or production-runtime behavior.

Examples

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

int main() {
    const std::array<int, 2> source{2, 3};
    std::vector<int> destination{1, 4};

    std::copy(source.begin(), source.end(),
              std::inserter(destination, destination.begin() + 1));

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

Result

1 2 3 4

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