std::next()는 <iterator> 헤더에 정의된 함수로, 주어진 이터레이터(iterator)를 원하는 횟수만큼 앞으로 이동한 새 이터레이터를 반환해준다.
함수 원형
template <class ForwardIterator>
ForwardIterator next(ForwardIterator x,
typename std::iterator_traits<ForwardIterator>::difference_type n = 1);
x : 이동할 기준이 되는 이터레이터n : 이동할 거리(기본값 1)반환값
n만큼 이동된 새로운 이터레이터를 반환한다.특징
x 자체를 변경하지 않는다. (call-by-value 형태로 파라미터를 받기 때문)n을 음수로 지정할 수 없다. (음수를 허용하는 것은 std::prev()가 담당)#include <iostream>
#include <vector>
#include <iterator> // std::next()가 선언된 헤더
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// vec.begin()를 기준으로 2만큼 앞선 위치의 이터레이터 반환
auto it = std::next(vec.begin(), 2);
std::cout << *it << std::endl; // 출력 결과: 3
return 0;
}
#include <iostream>
#include <list>
#include <iterator>
int main() {
std::list<int> myList = {10, 20, 30, 40, 50};
for (auto it = myList.begin(); it != myList.end(); ) {
// 다음 위치를 미리 계산
auto nextIt = std::next(it);
std::cout << *it << " ";
// it를 수동으로 증가시키는 대신 nextIt를 재활용할 수도 있음
it = nextIt;
}
// 출력: 10 20 30 40 50
return 0;
}
#include <iostream>
#include <vector>
#include <iterator>
int main() {
std::vector<int> data = {100, 200, 300, 400, 500};
// 벡터 크기가 충분하다고 가정할 때, 세 번째 원소 접근
auto third = std::next(data.begin(), 2);
std::cout << *third << std::endl; // 출력: 300
return 0;
}
범위 체크
이터레이터로 이동 가능한 범위를 벗어나지 않도록 주의해야 한다.
예를 들어, 컨테이너의 끝(end())을 넘어서는 거리만큼 std::next()를 사용하면 정의되지 않은 동작(UB, Undefined Behavior)이 발생한다.
음수 이동은 std::next()가 아닌 std::prev()
std::next()에 음수를 전달하는 것은 허용되지 않는다. 뒤로 이동하려면 std::prev()를 사용해야 한다.