Iterator

Jinyeong Choi·2024년 5월 31일

C++

목록 보기
3/5

Container

다른 객체(원소)들을 보관하는 하나의 커다란 보관소.
STL 컨테이너의 경우, 클래스 템플릿(class template)의 형태로 구현되어 있기 때문에, 임의의 타입의 원소들을 위한 컨테이너 생성 가능.
단, 한 컨테이너에는 한 가지 종류의 객체들만 보관할 수 있음.

  • 컨테이너는 자신이 보관하는 원소들의 메모리를 관리 및 각각의 원소에 접근할 수 있도록 멤버 함수를 제공.

컨테이너 상에서 원소에 접근하는 방법

  1. 직접 함수를 호출해서 접근하는 방법
  2. 반복자 iterator를 이용해서 접근하는 방법

What is Iterator?

Iterator

An object that allows a client to traverse and access elements.
반복자는 배열의 요소를 가리키는 포인터로,
C++ 라이브러리에서 제공해준 반복자를 이용하면 라이브러리의 방식대로 자료구조를 액세스 할 수 있다. 컨테이너에 저장되어 있는 원소들을 참조할 때 사용.

C++ defines two global funtions, std::begin and std::end, that produce iterators to the front and back of a data structure like a vector or static array.

  • begin()
    vector(data structure)의 첫 번째 요소를 가리키는 반복자를 반환하는 함수
  • end()
    vector(data structure)의 마지막 요소 바로 뒤의 요소를 가리키는 반복자를 반환하는 함수

STL 라이브러리에 포함되어 있는 begin과 end 함수의 반환값은 iterator로 아래와 같이 사용할 수 있다.

for (auto iter = begin(v); iter!= end(v); iter++){
	cout << *iter << " ";
}
cout << '\n';

정리하면, 반복자(iterator)란 저장되어 있는 모든 원소들을 전체적으로 훑어 나갈 때 사용하는 포인터와 유사한 객체.

Iterator의 성질

  • 컴테이너와 컨테이너 안에 있는 요소를 구별
  • 요소의 값 확인
  • 컨테이너 안에 있는 요소들 간에 이동할 수 있는 연산 제공
  • 컨테이너가 효과적으로 처리할 수 잇는 방식으로 가용한 연산들을 한정

Iterators provide the following methods:
_ operator _
used to access the element at the iterator's current position. (pointer dereferencing)

  • operator++
    used to move the iterator to the next element within the data structure. (pointer arithmetic)
  • operator!=
    used to determine whether two iterator objects currently refer to different elements within the data structure.

pointer dereference 역참조
주소를 통해 그 값에 접근하는 것
pointer arithmetic
a[ i ] = *( a + i )

profile
Hang in there

0개의 댓글