C++ iterator::distance() Function



The C++ iterator::distance() function is used to calculate the distance between two iterators. In other words, determine the number of elements between the two iterators using this function. The <iterator> header file is where the distance() function available.

It has an important characteristic like vectors, which have both magnitude and direction, distance() function also has direction associated to it. This indicates that calculating the distance between first and last and then calculating the distance between last and first will not be the same, as in the second case, it will have a negative sign associated with it, since we are travelling backwards.

Syntax

Following is the syntax for C++ iterator::distance() Function −

typename iterator_traits<InputIterator>::difference_type distance(InputIterator first, InputIterator last);

Parameters

  • first − Iterator that is pointing to the initial position.
  • last − Iterator that is pointing to the last position.

Example 1

Let's consider the following example, where we are going to use the distance() function and calculate first and last distance.

#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main() {
   vector<int> x;
   int y;
   for (y = 1; y < 8; ++y) {
      x.push_back(y);
   }
   vector<int>::iterator first;
   vector<int>::iterator last;
   first = x.begin();
   last = x.begin() + 3;
   int num = std::distance(first, last);
   cout << num << "\n";
   return 0;
}

Output

When we compile and run the above program, this will produce the following result −

3

Example 2

Consider the following example, where we are going to use distance() function and retrieving the output from last to first as a result it gives the negative number.

#include <iostream>
#include <vector>
#include <list>
using namespace std;
int main () {
   vector<int> Myvector = {2,4,6,8,10,12,14};
   int x = distance(Myvector.end(), Myvector.begin());
   cout << "The Result is: " << x;
   return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

The Result is: -7

Example 3

Look into the another scenario, where we are going to use distance()

#include <iostream>
#include <iterator>
#include <list>
int main () {
   std::list<int> mylist;
   for (int i = 0; i < 5; i++) mylist.push_back (i*1);
   std::list<int>::iterator first = mylist.begin();
   std::list<int>::iterator last = mylist.end();
   std::cout << "The distance between first and last is: " << std::distance(first,last) << '\n';
   return 0;
}

Output

On running the above program, it will produce the following result −

The distance between first and last is: 5
Advertisements