std::insert_iterator

std::insert_iterator (위치 삽입 반복자)

제공된 반복자가 가리키는 위치에 컨테이너에 요소를 삽입하는 LegacyOutputIterator예요. 반복자에 대입할 때마다 컨테이너의 insert() 멤버가 호출돼요. std::insert_iterator를 증가시키는 것은 no-op이에요.

출처: cppreference

본문

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

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

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

std::insert_iterator는 제공된 반복자가 가리키는 위치에 컨테이너에 요소를 삽입하는 LegacyOutputIterator예요. 반복자(역참조 여부와 무관)에 대입할 때마다 컨테이너의 insert() 멤버 함수가 호출돼요. std::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) — 위치 반복자와 함께 insert_iterator를 생성해요.
  • operator= — 가리키는 위치에 값을 삽입해요(c.insert(pos, value)).
  • operator*, operator++, operator++(int) — no-op으로 반복자 요구사항을 충족.

예제

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

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

더 알아보기 (Learn more)

cppreference