std::back_insert_iterator

std::back_insert_iterator (뒤쪽 삽입 반복자)

생성된 컨테이너에 요소를 추가(append)하는 LegacyOutputIterator예요. 반복자에 대입할 때마다 컨테이너의 push_back() 멤버가 호출돼요. std::back_insert_iterator를 증가시키는 것은 no-op이에요.

출처: cppreference

본문

<iterator> 헤더에 정의돼 있어요.

// C++17 이전
template< class Container >
class back_insert_iterator
    : public std::iterator<std::output_iterator_tag, void, void, void, void>;

// C++17부터
template< class Container >
class back_insert_iterator;

std::back_insert_iterator는 생성된 컨테이너에 요소를 추가하는 LegacyOutputIterator예요. 반복자(역참조 여부와 무관)에 대입할 때마다 컨테이너의 push_back() 멤버 함수가 호출돼요. std::back_insert_iterator를 증가시키는 것은 no-op이에요.

멤버 타입

멤버 타입 정의
iterator_category std::output_iterator_tag
value_type void
difference_type void (C++20까지) / std::ptrdiff_t (C++20부터)
pointer void
reference void
container_type Container

멤버 함수

  • (constructor) — 컨테이너에 대한 back_insert_iterator를 생성해요.
  • operator= — 컨테이너 끝에 값을 추가해요(c.push_back(value)).
  • operator*, operator++, operator++(int) — no-op, no-op, no-op으로 반복자 요구사항을 충족.

비멤버 함수

  • operator== (C++20) — 두 반복자를 비교(끝 반복자 판정).

예제

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

int main()
{
    std::vector<int> v{1, 2, 3};
    std::back_insert_iterator<std::vector<int>> it(v);
    it = 4; // v.push_back(4)
    for (int n : v) std::cout << n << ' '; // "1 2 3 4 "
}

더 알아보기 (Learn more)

cppreference