std::counted_iterator

std::counted_iterator (카운트 반복자)

기본 반복자와 정확히 같게 동작하되, 범위 끝까지의 거리를 추적하는 반복자 어댑터예요. 카운트가 0이 되면 std::default_sentinel과 같아져요. C++20부터 있어요.

출처: cppreference

본문

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

template< std::input_or_output_iterator I >
class counted_iterator;

std::counted_iterator는 기본 반복자와 정확히 같게 동작하되, 범위 끝까지의 거리를 추적하는 반복자 어댑터예요. 이 반복자는 카운트가 0에 도달할 때에만 std::default_sentinel과 같아져요.

멤버 타입

멤버 타입 정의
iterator_type I
value_type Iindirectly_readable을 모델링하면 std::iter_value_t<I>, 아니면 정의되지 않음
difference_type std::iter_difference_t<I>
iterator_concept I::iterator_concept(있으면)
iterator_category I::iterator_category(있으면)

멤버 객체

  • current (private, exposition-only) — base()가 접근하는 기본 반복자.
  • length (private, exposition-only) — 기본 반복자와 범위 끝 사이의 거리.

멤버 함수

  • (constructor) — 새 counted_iterator를 생성해요.
  • operator= — 다른 counted_iterator를 할당해요.
  • base — 기본 반복자에 접근해요.
  • count — 범위 끝까지 남은 거리를 돌려줘요.
  • operator*, operator-> — 가리키는 요소에 접근해요.
  • operator++ — 전진해요.

예제

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

int main()
{
    std::vector<int> v{1, 2, 3, 4, 5};
    auto it = std::counted_iterator(v.begin(), 3);
    // 처음 3개 요소만 범위로 취급
    std::ranges::copy(it, std::default_sentinel,
                      std::ostream_iterator<int>(std::cout, " "));
    // "1 2 3 "
}

더 알아보기 (Learn more)

cppreference