function template
<iterator>

std::advance

template <class InputIterator, class Distance>  void advance (InputIterator& it, Distance n);
Advance iterator
Advances the iterator it by n element positions.

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--) until n elements have been advanced.

Parameters

it
Iterator to be advanced.
InputIterator shall be at least an input iterator.
n
Number of element positions to advance.
This shall only be negative for random-access and bidirectional iterators.
Distance shall be a numerical type able to represent distances between iterators of this type.

Return value

none

Example

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

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

  std::list<int>::iterator it = mylist.begin();

  std::advance (it,5);

  std::cout << "The sixth element in mylist is: " << *it << '\n';

  return 0;
}

Output:

The sixth element in mylist is: 50


Complexity

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

Iterator validity

Advancing an input iterator that is not at least a forward iterator may invalidate any iterators, pointers and references obtained from its value.

Data races

The function modifies the iterator, but it is never dereferenced (no pointed object is accessed by the call).
Note also the effects on iterator validity described above.

Exception safety

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

See also