std::back_insert_iterator - cppreference.com

From cppreference.com

Defined in header <iterator>

template< class Container > class back_insert_iterator : public std::iterator<std::output_iterator_tag, void, void, void, void>

(until C++17)

template< class Container > class back_insert_iterator;

(since C++17)

std::back_insert_iterator is a LegacyOutputIterator that appends elements to a container for which it was constructed. The container's push_back() member function is called whenever the iterator (whether dereferenced or not) is assigned to. Incrementing the std::back_insert_iterator is a no-op.

Member types

Member type Definition
iterator_category std::output_iterator_tag
value_type void
difference_type

void

(until C++20)

std::ptrdiff_t

(since C++20)
pointer void
reference void
container_type Container

Member types iterator_category, value_type, difference_type, pointer and reference are required to be obtained by inheriting from std::iterator<std::output_iterator_tag, void, void, void, void>.

(until C++17)

Member functions

Member objects

Member name Definition
container (protected) a pointer of type Container*

Example

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

int main()
{
    std::vector<int> v;

    std::generate_n(
        std::back_insert_iterator<std::vector<int>>(v),
            // Or use std::back_inserter helper
            // Or use std::back_insert_iterator(v) C++17's syntax
        10,
        [n = 0]() mutable { return ++n; }
    );

    for (int n : v)
        std::cout << n << ' ';
    std::cout << '\n';
}

Output:

See also