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.
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.
The distance()
function returns the number of elements between first
and last
.
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;}
distance()
function and pass the two iterators.