function template

std::distance

<iterator>
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 i 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.
second
Iterator pointing to the final element. This must be reachable from first.

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
17
// distance example
#include <iostream>
#include <iterator>
#include <list>
using namespace std;

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

  list<int>::iterator first = mylist.begin();
  list<int>::iterator last = mylist.end();

  cout << "The distance is: " << distance(first,last) << endl;

  return 0;
}


Output

The distance is: 10

Complexity

Constant for random access iterators.
Linear on the return value for other categories of iterators.

See also