std::distance() in C++
The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and direction and so many essential features. It is used to calculate the distance between the first and last points. Suppose, we move in a backward direction, and then a negative sign is associated with it.
Syntax:
std::distance(InputIterator first, InputIterator last)
Here, first and last are input iterators between which we have to calculate distance.
Returns: The number of elements between first and last.
Example:
Input: p = 5 6 7 8 9 10
first pointing to p.begin() and last pointing to p.end()
Output:
No. of elements: 6
C++ Example 1:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector<int> p;
int i;
for (i = 0; i < 10; ++i)
{
p.push_back(i);
}
vector<int>::iterator first;
vector<int>::iterator last;
first = p.begin();
last = p.begin() + 8;
int num = std::distance(first, last);
cout << num <<"\n";
return 0;
}
Output:
See, what happens when we reverse the order while calculating distance?
C++ Example 2:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector<int> p;
int i;
for (i = 0; i < 8; ++i)
{
p.push_back(i);
}
int num = std::distance(p.begin(), p.end());
cout << num <<"\n";
num = std::distance(p.end(), p.begin());
cout << num <<"\n";
return 0;
}
Output