배움 저장소
[C++] Iterator 본문
Set up for C++ 17
- MSVC을 Command Line으로 실행한다면 "/std:c++17",를 추가해주어야 한다.
- "/std:c++20"이나 "/std:c++latest"를 사용할 수도 있다.
1. Range Based 반복문.
vector<int> v = {0,1,2,3,4};
for(int value : v)
std::cout << value << std::endl;
// 값을 복사하지 않음. 변경이 가능함.
for(int &value : v)
std::cout << value << std::endl;
// 값을 복사하지 않음. 변경이 불가능함.
for(const int &value : v)
std::cout << value << std::endl;
2. 위 코드의 for 반복문은 간단하고 읽기도 좋다. 이렇게 간단한 코드는 어떻게 동작하고 있을까? vector는 begin()과 end()을 사용하여 Iterator를 반환할 수 있다. 위 코드는 사실 아래 코드를 간단하게 사용할 수 있도록 한 것이다.
for(vector<int>::iterator itr=v.begin(); itr!=v.end(); ++itr)
{
std::cout << *itr << std::endl;
}
3. vector<int>::iterator가 길다면 간단하게 macro를 사용할 수도 있다.
using simple_itr = vector<int>::iterator;
for(simple_itr itr = v.begin(); itr!=v.end(); ++itr)
using simple_v = vector<int>;
for(simple_v::iterator itr = v.begin(); itr!=v.end(); ++itr)
4. Iterator는 Index가 존재하지않는 unordered_map이나 Tree 같은 타입에서 유용하게 쓸 수 있다.
#include <vector>
#include <iostream>
#include <string>
#include <unordered_map>
using umap = unordered_map<string, int>;
int main()
{
unordered_map<string, int> map;
map["A"] = 0;
map["B"] = 10;
map["C"] = 20;
for(unordered_map<string, int>::iterator itr= map.begin(); itr!=map.end(); ++itr)
std::cout << itr->first << " " << itr->second << std::endl;
for(umap::iterator itr = map.begin(); itr!=map.end(); ++itr)
std::cout << itr->first << " " << itr->second << std::endl;
for(auto& kv : map)
{
auto& key = kv.first;
auto& value = kv.second;
std::cout << key << " auto " << value << std::endl;
}
}
5. 위의 마지막 반복문 코드를 더 간단하게 만들 수 있다. c++17에서는 structure binding을 지원한다.
// range based loop, c++ 17 version
for(auto [key,value] : map)
{
std::cout << key << " auto c17 " << value << std::endl;
}
// Test with Iterator
for(auto [key,value] : map)
{
if(key == "B")
{
map.insert(map.end(), pair<string, int>("E",100));
map.erase("C");
}
std::cout << key << " auto c17 " << value << std::endl;
}
'Programming Language > C++' 카테고리의 다른 글
[홍정모의 따라하며 배우는 C++] 0. 시작해봅시다. (0) | 2021.12.10 |
---|---|
[C++] Template (0) | 2021.11.13 |
[C/C++] Left Shift and Right Shift (0) | 2021.11.11 |
[C++] unique_ptr, shared_ptr, weak_ptr (0) | 2021.11.07 |
부호가 있는 이진수 1000은 0일까? (0) | 2021.10.19 |