![]() |
VOOZH | about |
The std::distance() in C++ STL is a built-in function used to calculate the number of elements between two iterators. It is defined inside <iterator> header file. In this article, we will learn about the std::distance function in C++ with examples.
Example:
5
std::distance(first, last);
The std::distance() function calculates the distance between two iterators by iterating from the first iterator to the last. For random-access iterators, such as those used by vectors and deques, the calculation is done in constant time (O(1)). For other types of iterators, such as those for lists or sets, it has a linear time complexity of O(n).
The following examples demonstrates the use of std::distance() function in different scenarios:
4
Time Complexity: O(1)
Auxiliary Space: O(1)
5
Time Complexity: O(1)
Auxiliary Space: O(1)
4
Time Complexity: O(n), where n is the number of elements between the two iterators of std::set.
Auxiliary Space: O(1)
-5
10
Time Complexity: O(1)
Auxiliary Space: O(1)
Explanation: In this example, we have taken the iterators to two different vectors, and got the output as 10. But this information is pretty useless for a regular person as there is no guarantee that the vectors declared subsequently will be stored continuously after the previous one.