// 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
Code Example |
---|
Cpp :: how to find 2d vector length cpp |
Cpp :: stl sort in c++ |
Cpp :: c++ vectors |
Cpp :: c++ remove text file |
Cpp :: set clear c++ |
Cpp :: c++ fstream |
Cpp :: cstring to string |
Cpp :: check if set contains element c++ |
Cpp :: c++ cstring to string |
Cpp :: factorial function c++ |
Cpp :: sort vector struct c++ |
Cpp :: opencv open image c++ |
Cpp :: sorting using comparator in c++ |
Cpp :: sina + sinb formula |
Cpp :: min heap priority queue c++ |
Cpp :: number of digits in int c++ |
Cpp :: json::iterator c++ |
Cpp :: #define online judge in cpp |
Cpp :: string search c++ |
Cpp :: Search Insert Position leetcode solution in cpp |
Cpp :: Disabling console exit button c++ |
Cpp :: login system with c++ |
Cpp :: c++ clip values |
Cpp :: c++ loop through list |
Cpp :: getline() |
Cpp :: explicit c++ |
Cpp :: how to have a queue as a parameter in c++ |
Cpp :: cpp execute command |
Cpp :: initialising 2d vector |
Cpp :: 1768. Merge Strings Alternately leetcode solution in c++ |