CKTIS / C++
std::back_insert_iterator — appending through an output iterator
std::back_insert_iterator is an output iterator adaptor that turns value assignment into a container push_back call. It lets you append elements using *out++ = value without overwriting existing elements.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <iterator>
std::back_insert_iterator<Container> out(container);
*out++ = value;
// Equivalent factory:
auto out2 = std::back_inserter(container);std::back_insert_iterator<Container>, declared in <iterator>, is an output iterator adaptor. Its constructor takes Container& and stores the container's address; the adaptor does not own it. The container must remain alive while the adaptor is used and provide the appropriate push_back operation.
Assigning a value through the adaptor appends an element: the overload for const Container::value_type& calls push_back(value), while the overload for Container::value_type&& calls push_back(std::move(value)). operator* returns the adaptor itself, not an element reference. The ++ operators neither advance a position nor add elements; consequently, *out++ = value appends exactly one element.
This is a tool for writing, not for reading or traversing elements. It appends new elements rather than overwriting existing ones. The function std::back_inserter(container) creates the same kind of adaptor without explicitly naming the container type.
In the example, the container initially holds 10, and two assignments append 20 and 30. The code is intended for local compilation with -std=c++23. The cited pages present the evolving working draft, not a frozen C++23 publication.
Examples
#include <cstddef>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> values{10};
std::back_insert_iterator<std::vector<int>> out(values);
*out++ = 20;
*out++ = 30;
for (std::size_t i = 0; i < values.size(); ++i) {
if (i != 0) {
std::cout << ' ';
}
std::cout << values[i];
}
std::cout << '\n';
}
Result
10 20 30
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.