◐ Shell
clean mode source ↗

std::next - cppreference.com

提供: cppreference.com

<tbody> </tbody>

ヘッダ <iterator> で定義

template< class ForwardIt > ForwardIt next( ForwardIt it, typename std::iterator_traits<ForwardIt>::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 個分インクリメントしたイテレータを返します。

引数

it - イテレータ
n - 進める要素数
型の要件
-ForwardItLegacyForwardIterator の要件を満たさなければなりません。
-InputItLegacyInputIterator の要件を満たさなければなりません。

戻り値

イテレータ it を要素 n 個分インクリメントしたイテレータ。

計算量

線形。

ただし、 InputIt または ForwardItLegacyRandomAccessIterator の要件を追加で満たす場合、計算量は定数です。

実装例

template<class ForwardIt>
ForwardIt next(ForwardIt it,
               typename std::iterator_traits<ForwardIt>::difference_type n = 1)
{
    std::advance(it, n);
    return it;
}

ノート

++c.begin() はわりとコンパイルできますが、保証されてはいません。 c.begin() は右辺値の式であり、 LegacyBidirectionalIterator の要件は右辺値のインクリメントが動作することを保証するとは規定していません。 特に、イテレータがポインタとして実装されている場合、 ++c.begin() はコンパイルできませんが、 std::next(c.begin()) はできます。

#include <iostream>
#include <iterator>
#include <vector>

int main() 
{
    std::vector<int> v{ 3, 1, 4 };
    
    auto it = v.begin();

    auto nx = std::next(it, 2);

    std::cout << *it << ' ' << *nx << '\n';
}

出力:

関連項目