If we have two iterators and we want to find the total no. of elements between the two iterators, then that is facilitated by std::distance(), defined inside the header file .
It has an important feature that just like we have vectors in science, which have both magnitude and direction, std::distance also has direction associated with it. This means that calculating the distance between first and last and then calculating distance between last and first will not be same, as in the second case, it will have a negative sign associated with it, since we are moving backwards.
std::distance(InputIterator first, InputIterator last) Here, first and last are input iterators between which we have to calculate distance. Returns: The number of elements between first and last.
Input: v = 10 20 30 40 50 first pointing to v.begin() and last pointing to v.end() Output: No. of elements: 5
What happens when we reverse the order while calculating distance?
Since, it counts the no. of elements between the two input iterators, one thing to be kept in mind is that it does not count the element being pointed to by last (if any), while calculating the distance, whereas element pointed to by first is counted i,e range is [first,last).
Here, total number of elements between first (pointing to 0) and last (pointing to 5) is 5, i.e., 0 1 2 3 4. So element pointed to by last has not been counted by distance().
Time Complexity: Constant for random-access iterators and O(n) for all other iterators.
This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Vector of Vectors in C++ STL with Examples
- Array of Vectors in C++ STL
- Difference between Virtual function and Pure virtual function in C++
- cin get() in C++ with Examples
- Difference between Increment and Decrement Operators
- Map of Vectors in C++ STL with Examples
- Problem in comparing Floating point numbers and how to compare them correctly?
- exit(0) vs exit(1) in C/C++ with Examples
- C++ program to print all Even and Odd numbers from 1 to N
- Reverse the content of a file and store it in another
- Minimum cells to be flipped to get a 2*2 submatrix with equal elements
- Cyclic Iterator for K variable length vectors
- Nested Loops in C++ with Examples
- _Find_first() function in C++ bitset with Examples
- _Find_next() function in C++ bitset with Examples