Top of document
©Copyright 1999 Rogue Wave Software

distance


     Iterator Operation

Summary

Computes the distance between two iterators


Contents

Synopsis

#include <iterator>
template <class InputIterator, class Distance>
 void distance (InputIterator first,
                InputIterator last,
                Distance& n);

Description

The distance template function computes the distance between two iterators and stores that value in n. The last iterator must be reachable from the first iterator.

distance increments n by the number of times it takes to get from first to last. distance must be a three argument function that stores the result into a reference instead of returning the result, because the distance type cannot be deduced from built-in iterator types such as int*.

Example

//
// distance.cpp
//
 #include <iterator>
 #include <vector>
 #include <iostream.h> 

int main()
 {
   //
   //Initialize a vector using an array
   //
   int arr[6] = {3,4,5,6,7,8};
   vector<int> v(arr,arr+6);
   //
   //Declare a list iterator, s.b. a ForwardIterator
   //
   vector<int>::iterator itr = v.begin()+3;
   //
   //Output the original vector
   //
   cout << "For the vector: ";
   copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
   cout << endl << endl;
   cout << "When the iterator is initialized to point to "
        << *itr << endl;
   //
   // Use of distance
   //
   vector<int>::difference_type dist = 0;
   distance(v.begin(), itr, dist);
   cout << "The distance between the beginning and itr is " 
        << dist << endl;
   return 0;
 }
Output : 
For the vector: 3 4 5 6 7 8
When the iterator is initialized to point to 6
The distance between the beginning and itr is 3

Warning

If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write:

vector <int, allocator>

instead of:

vector <int>

See Also

Sequences, Random Access Iterators


Top of document