// C++ program to demonstrate std::distance()
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector<int> v;
int i;
for (i = 0; i < 10; ++i)
{
v.push_back(i);
}
/*v contains 0 1 2 3 4 5 6 7 8 9*/
vector<int>::iterator first;
vector<int>::iterator last;
// first pointing to 0
first = v.begin();
// last pointing to 5
last = v.begin() + 5;
// Calculating no. of elements between first and last
int num = std::distance(first, last);
// Displaying num
cout << num << "
";
return 0;
}
// Calculates the number of elements between first and last.
#include <iterator> // std::distance
#include <vector> // std::vector
#include <algorithm> // Just if you use std::find
vector<int> arr = {2,5,3,8,1};
int size = std::distance(arr.begin(), arr.end()); // 5
auto it = std::find(arr.begin(), arr.end(), 8);
int position = std::distance(arr.begin(), it); // 3