What is the distance() function in C++?
The distance() function in C++ helps find the distance between two iterators. In other words, we can use this function to calculate the number of elements present between the two iterators. This function is available in the <iterator> header file.
Parameters
The distance() function accepts the following parameters.
-
first: This is an iterator that points to the initial position of the array or vector. -
last: This is an iterator that points to the last position of the array or vector.
Return
The distance() function returns the number of elements between first and last.
Code
Let’s look at the code now.
#include <iostream>#include <vector>#include <list>using namespace std;int main () {vector<int> vec = {1,2,3,4,5,6,7,8,9,10};int dist = distance(vec.begin(), vec.end());cout << "The distance is: " << dist;return 0;}
Explanation
- From lines 1 to 3, we import the required header files.
- In line 7, we create a vector that contains some integer values.
- In line 9, we call the
distance()function and pass the two iterators. - In line 11, we print the number of elements present between the two iterators.