Skip to content. Skip to navigation

ICTP Portal

Sections
You are here: Home Manuals on-line PGI Compiler pgC_lib distance
Personal tools
Document Actions

distance



Click on the banner to return to the class reference home page.

distance


Iterator Operation

Summary

Computes the distance between two iterators

Data Type and Member Function Indexes
(exclusive of constructors and destructors)

None

Synopsis

#include <iterator>

template <class ForwardIterator>
 iterator_traits<ForwardIterator>::distance_type
 distance (ForwardIterator first,
                ForwardIterator last);

template <class ForwardIterator, class Distance>
 void distance (ForwardIterator first,
                ForwardIterator last,
                Distance& n);

Description

The distance template function computes the distance between two iterator. The first version returns that value, while the second version increments n by that value. The last iterator must be reachable from the first iterator.

Note that the second version of this function is obsolete. It is provided for backward compatibility and to support compilers that do not provide partial specialization. As you may have already deduced, the first version of the function is not available with compilers that do not support partial specialization since it depends on iterator_traits, which itself depends on that particular language feature.

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,char>(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,int> >

instead of:

vector <int>

Also, if your compiler does not support partial specialization then you will not be able to use the version of distance that returns the distance. Instead you'll have to use the version that increments a reference parameter.

See Also

Sequences, Random Access Iterators


©Copyright 1996, Rogue Wave Software, Inc.

Weather
No information available
 

Powered by Plone This site conforms to the following standards: