function template
<iterator>

std::next

template <class ForwardIterator>
  ForwardIterator next (ForwardIterator it,
       typename iterator_traits<ForwardIterator>::difference_type n = 1);
Get iterator to next element
Returns an iterator pointing to the element that it would be pointing to if advanced n positions.

it is not modified.

If it is a random-access iterator, the function uses just once operator+ or operator-. Otherwise, the function uses repeatedly the increase or decrease operator (operator++ or operator--) on the copied iterator until n elements have been advanced.

Parameters

it
Iterator to base position.
ForwardIterator shall be at least a forward iterator.
n
Number of element positions offset (1 by default).
This shall only be negative for random-access and bidirectional iterators.
difference_type is the numerical type that represents distances between iterators of the ForwardIterator type.

Return value

An iterator to the element n positions away from it.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// next example
#include <iostream>     // std::cout
#include <iterator>     // std::next
#include <list>         // std::list
#include <algorithm>    // std::for_each

int main () {
  std::list<int> mylist;
  for (int i=0; i<10; i++) mylist.push_back (i*10);

  std::cout << "mylist:";
  std::for_each (mylist.begin(),
                 std::next(mylist.begin(),5),
                 [](int x) {std::cout << ' ' << x;} );

  std::cout << '\n';

  return 0;
}


Output:

mylist: 0 10 20 30 40

Complexity

Constant for random-access iterators.
Otherwise, linear in n.

Iterator validity

No effect.

Data races

The function accesses the iterator, but it is never dereferenced (no pointed object is accessed by the call).

Exception safety

Throws if any of the arithmetical operations performed on the copied iterator throws, providing the same level of guarantee as such operations.

See also