728x90
C++에서 다양한 유형의 이터레이터(Input, Output, Forward, Bidirectional, Random Access)를 각각 설명하고
예제를 제공하겠습니다.
이 예제들은 이터레이터의 기능적 차이를 보여주고, 어떻게 각각의 이터레이터를 사용할 수 있는지를 설명합니다.
Input Iterator
'istream_iterator'는 입력 이터레이터의 일반적인 예입니다.
표준 입력에서 정수 값을 읽습니다.
#include <iostream>
#include <iterator>
int main() {
std::cout << "Enter numbers: ";
std::istream_iterator<int> it(std::cin);
std::istream_iterator<int> end;
while (it != end) {
std::cout << "You entered: " << *it << std::endl;
++it;
}
}
Output Iterator
'ostream_iterator'는 출력 이터레이터의 예로,
표준 출력으로 값을 출력합니다.
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::ostream_iterator<int> output_it(std::cout, " ");
std::copy(numbers.begin(), numbers.end(), output_it);
}
Forward Iterator
'forward_list' 사용 예제로,
이 리스트는 단방향 이터레이터만을 지원합니다.
#include <forward_list>
#include <iostream>
int main() {
std::forward_list<int> flist = {10, 20, 30, 40};
for (auto it = flist.begin(); it != flist.end(); it++) {
std::cout << *it << " ";
}
std::cout << std::endl;
}
Bidirectional Iterator
'list'와 'set'은 양방향 이터레이터를 사용합니다.
여기서는 'list'를 사용합니다.
#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
// 순방향으로 반복
for (auto it = numbers.begin(); it != numbers.end(); it++) {
std::cout << *it << " ";
}
std::cout << std::endl;
// 역방향으로 반복
for (auto rit = numbers.rbegin(); rit != numbers.rend(); rit++) {
std::cout << *rit << " ";
}
std::cout << std::endl;
}
Random Access Iterator
'vector'와 'deque'는 임의 접근 이터레이터를 제공합니다.
여기서는 'vector'를 사용합니다.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// 임의 접근
std::cout << "The fifth element: " << numbers[4] << std::endl;
// 임의 접근 이터레이터를 이용한 요소 접근 및 변경
auto it = numbers.begin() + 5;
std::cout << "Element at position 5: " << *it << std::endl;
// 이터레이터를 사용한 요소 간 산술 연산
auto distance = std::distance(numbers.begin(), it);
std::cout << "Distance from beginning to fifth element: " << distance << std::endl;
}
마무리
이 예제들은 각 유형의 이터레이터가 어떻게 작동하는지를 보여주며,
특정 상황에서 어떤 이터레이터가 유용한지 이해하는 데 도움을 줍니다.
각 이터레이터는 C++의 STL 컨테이너와 함께 사용될 때 특히 강력하며,
데이터 구조에 대한 추상화된 접근을 제공합니다.
제 글이 도움이 되셨다면 댓글 & 공감 부탁드려요 😀
728x90
반응형
'Application > 기초' 카테고리의 다른 글
| [기초] C++ 알고리즘 : 선택 정렬 (Selection Sort) (0) | 2024.05.05 |
|---|---|
| [기초] C++ 알고리즘 : 버블 정렬 (Bubble Sort) (0) | 2024.05.04 |
| [기초] C++ 컨테이너 (Containers) (0) | 2024.05.02 |
| [기초] C++ this 포인터 : 객체의 자기 참조 (0) | 2024.05.01 |
| [기초] C++ 동기화 기법 (Mutex와 Semaphore) (0) | 2024.04.30 |