std distance code example
Example 1: std distance c++
// C++ program to demonstrate std::distance()
#include
#include
#include
using namespace std;
int main()
{
vector 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::iterator first;
vector::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 << "\n";
return 0;
}
Example 2: std distance
// Calculates the number of elements between first and last.
#include // std::distance
#include // std::vector
#include // Just if you use std::find
vector 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