function template
<iterator>

std::distance

template<class InputIterator>  typename iterator_traits<InputIterator>::difference_type    distance (InputIterator first, InputIterator last);
Return distance between iterators
Calculates the number of elements between first and last.

If it is a random-access iterator, the function uses operator- to calculate this. Otherwise, the function uses the increase operator (operator++) repeatedly.

Parameters

first
Iterator pointing to the initial element.
last
Iterator pointing to the final element. This must be reachable from first.
InputIterator shall be at least an input iterator.

Return value

The number of elements between first and last.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// advance example
#include <iostream>     // std::cout
#include <iterator>     // std::distance
#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 first = mylist.begin();
  std::list<int>::iterator last = mylist.end();

  std::cout << "The distance is: " << std::distance(first,last) << '\n';

  return 0;
}

Output:

The distance is: 10


Complexity

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

Iterator validity

If InputIterator is not at least a forward iterator, first and any iterators, pointers and references obtained from its value may be invalidated.

Data races

The function accesses both iterators, but none is 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