CKTIS / C++
std::back_inserter: algorithm output that appends
std::back_inserter creates an output iterator whose assignment calls push_back on the referenced container.
Version: C++23
Syntax
template<class Container>
constexpr std::back_insert_iterator<Container> back_inserter(Container& container);std::back_inserter(container) from <iterator> returns a std::back_insert_iterator that stores a pointer to the container. Assignment through it performs container.push_back(value) or moves an rvalue, so an algorithm can produce elements without pre-sizing the destination. std::back_inserter is the helper function that constructs this adaptor for the supplied container.
The container must provide a compatible push_back; the adaptor therefore does not work with std::array, for example. Dereference and increment are protocol operations that return the adaptor itself, so successive assignments append successive elements.
Each append may allocate, throw, and invalidate ordinary iterators or references into the container. The adaptor itself still points to the container, not its buffer. When the result count is known, reserve can reduce reallocations without changing algorithm semantics.
Examples
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> values{2};
auto output = std::back_inserter(values);
*output = 5;
++output;
std::cout << values.front() << ' ' << values.back() << '\n';
}
Result
2 5
std::back_inserter → 2 5