Namespaces
Variants

std:: next

From cppreference.net
Iterator library
Iterator concepts
Iterator primitives
Algorithm concepts and utilities
Indirect callable concepts
Common algorithm requirements
(C++20)
(C++20)
(C++20)
Utilities
(C++20)
Iterator adaptors
Range access
(C++11) (C++14)
(C++14) (C++14)
(C++11) (C++14)
(C++14) (C++14)
(C++17) (C++20)
(C++17)
(C++17)
헤더 파일에 정의됨 <iterator>
template < class InputIt >
InputIt next ( InputIt it, typename std:: iterator_traits < InputIt > :: difference_type n = 1 ) ;
(C++11부터)
(C++17까지)
template < class InputIt >

constexpr

InputIt next ( InputIt it, typename std:: iterator_traits < InputIt > :: difference_type n = 1 ) ;
(C++17부터)

이터레이터 it n 번째 후속자(또는 - n 번째 선행자, 만약 n 이 음수인 경우)를 반환합니다.

목차

매개변수

it - 반복자
n - 진행할 요소의 개수
타입 요구사항
-
InputIt LegacyInputIterator 요구사항을 충족해야 합니다.

반환값

InputIt 타입의 반복자로, 반복자 it n 번째 후속자(또는 - n 번째 선행자, 만약 n 이 음수인 경우)를 보유합니다.

복잡도

선형.

그러나 InputIt 가 추가적으로 LegacyRandomAccessIterator 요구사항을 충족하는 경우, 복잡도는 상수입니다.

가능한 구현

template<class InputIt>
constexpr // C++17부터
InputIt next(InputIt it, typename std::iterator_traits<InputIt>::difference_type n = 1)
{
    std::advance(it, n);
    return it;
}

참고 사항

표현식 ++ c. begin ( ) 가 종종 컴파일되기는 하지만, 이것이 보장되지는 않습니다: c. begin ( ) 는 rvalue 표현식이며, rvalue의 증가가 작동한다는 것을 보장하는 LegacyInputIterator 요구 사항이 존재하지 않습니다. 특히, 반복자가 포인터로 구현되거나 operator++ 가 lvalue-ref-qualified인 경우, ++ c. begin ( ) 는 컴파일되지 않는 반면, std :: next ( c. begin ( ) ) 는 컴파일됩니다.

예제

#include <iostream>
#include <iterator>
#include <vector>
int main()
{
    std::vector<int> v{4, 5, 6};
    auto it = v.begin();
    auto nx = std::next(it, 2);
    std::cout << *it << ' ' << *nx << '\n';
    it = v.end();
    nx = std::next(it, -2);
    std::cout << ' ' << *nx << '\n';
}

출력:

4 6
 5

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 2353 C++11 next 요구사항 LegacyForwardIterator LegacyInputIterator 허용

참고 항목

(C++11)
반복자를 감소시킴
(함수 템플릿)
주어진 거리만큼 반복자를 전진시킴
(함수 템플릿)
두 반복자 사이의 거리를 반환함
(함수 템플릿)
주어진 거리만큼 또는 경계까지 반복자를 증가시킴
(알고리즘 함수 객체)