distance() in C++ STL

The C++ Standard Library consists of the header, <iterator>. An iterator is an object that points to an element in a range of elements. The most obvious form of an iterator is a pointer. The distance() method is present under this header and it calculates the number of elements between two iterators.

Syntax:

distance( iterator_begin, iterator_end );

Parameters: The distance() method accepts 2 parameters

  • iterator_begin: Iterator to the initial element
  • iterator_end: Iterator to the final element (Note: It must be reachable from iterator_begin)

Return value: Number of elements between the two iterators

Example of distance() method

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    vector<int> v;
    v.push_back(3);
    v.push_back(2);
    v.push_back(1);
    v.push_back(4);
    v.push_back(5);

    vector<int>::iterator it1= v.begin();
    vector<int>::iterator it2= v.begin()+3;

    cout<<"No. of elements between it1 and it2: "<< distance(it1, it2);
}

Output:

No. of elements between it1 and it2: 3

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top