std::distance
is a function in the C++ standard library used to calculate the distance between two iterators, that is, the number of elements from one iterator to another iterator. It can be used for iterators of various containers (such asstd::vector
、std::list
wait).
grammar
#include <iterator> std::distance(iterator1, iterator2);
parameter:
-
iterator1
: Start iterator. -
iterator2
: End the iterator.
Return value:
- return
iterator1
anditerator2
The number of elements between them (i.e. the distance between them).
How to use
Here is a simple example that demonstrates how to usestd::distance
:
#include <iostream> #include <vector> #include <iterator> // std::distance int main() { std::vector<int> vec = {10, 20, 30, 40, 50}; // Get the distance between two iterators auto it1 = (); auto it2 = (); // Calculate the distance from it1 to it2 std::cout << "Distance between it1 and it2: " << std::distance(it1, it2) << std::endl; // Get the index position of the element auto it3 = () + 2; // Point to the third element std::cout << "Distance from begin to it3: " << std::distance(it1, it3) << std::endl; return 0; }
explain
-
std::distance(it1, it2)
:returnit1
arriveit2
The number of elements between them. -
it1
It is pointing to the containervec
The iterator at the start position,it2
It is pointing to the containervec
The iterator at the end position (i.e.()
)。 - The return value is
5
,expressit1
arriveit2
There are 5 elements between them.
Sample output:
Distance between it1 and it2: 5
Distance from begin to it3: 2
Other Instructions:
Time complexity:std::distance
The time complexity is related to the container type. If it is a random access iterator (such asstd::vector
), the time complexity is O(1). If it is a bidirectional or forward iterator (such asstd::list
), the time complexity is O(n), where n is the number of elements between two iterators.
Notice: For non-random accessed containers (such asstd::list
orstd::set
),std::distance
It may involve traversals one by one, so it is less efficient.
Summarize
std::distance
It is a function used to calculate the number of elements between two iterators, which is often used to obtain the index position between two elements in a container or calculate the offset.
This is the article about the use of std::distance in C++. For more related C++ std::distance content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!