distance cpp code example
Example 1: std distance c++
#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);
}
vector<int>::iterator first;
vector<int>::iterator last;
first = v.begin();
last = v.begin() + 5;
int num = std::distance(first, last);
cout << num << "\n";
return 0;
}
Example 2: std distance
#include <iterator>
#include <vector>
#include <algorithm>
vector<int> arr = {2,5,3,8,1};
int size = std::distance(arr.begin(), arr.end());
auto it = std::find(arr.begin(), arr.end(), 8);
int position = std::distance(arr.begin(), it);