C++/C++
반복자 다루기
Elan
2021. 3. 26. 06:13
Iterator 를 조금 더 쉽게 컨트롤 할 수 있는 방법이 있다.
std::next
- 반복자를 n 만큼 다음으로 이동하고
std::pre
- 반복자를 n 만큼 이전으로 이동한다.
std::begin
- 컨테이너의 시작 포인터를 반환한다.
std::end
- 컨테이너의 끝의 포인터를 반환한다.
std::vector<int> v{ 1,2,3,4,5 };
auto it = v.begin();
auto next = std::next(it, 2);//begin에서 2칸 다음으로 넘기기
std::cout << *it << ", " << *next << std::endl;
auto pre = std::prev(next, 2);//next에서 2칸 앞으로 넘기기
std::cout << *next << ", " << *pre<< std::endl;
std::vector<int> v2{ 2,4,6,8 };
for (auto it = std::begin(v2); it != std::end(v2); ++it) {
std::cout << *it << std::endl;
}
iterator에 대한 가독성이 더 좋아진것을 볼 수 있다.
기존에는 아래와 같이 사용했을 것이다.
std::vector<int> v{ 1,2,3,4,5 };
auto it = v.begin();
//auto next = std::next(it, 2);//begin에서 2칸 다음으로 넘기기
auto next = it+2;
std::cout << *it << ", " << *next << std::endl;
auto pre = next-2;//next에서 2칸 앞으로 넘기기
std::cout << *next << ", " << *pre<< std::endl;
std::vector<int> v2{ 2,4,6,8 };
for (auto it = v2.begin(); it != v2.end(); ++it) {
std::cout << *it << std::endl;
}
next와 pre가 뭔지 얼핏 봐서는 모르겠다.
코드가 간결해지진 않았지만 가독성이 한결 업그레이드 되었다고 생각한다.