SoFunction
Updated on 2025-04-14

Example of usage method of std::distance in C++

std::distanceis 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::vectorstd::listwait).

grammar

#include <iterator>

std::distance(iterator1, iterator2);

parameter

  • iterator1: Start iterator.
  • iterator2: End the iterator.

Return value

  • returniterator1anditerator2The 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 &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;iterator&gt;  // std::distance

int main() {
    std::vector&lt;int&gt; 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 &lt;&lt; "Distance between it1 and it2: " &lt;&lt; std::distance(it1, it2) &lt;&lt; std::endl;

    // Get the index position of the element    auto it3 = () + 2;  // Point to the third element    std::cout &lt;&lt; "Distance from begin to it3: " &lt;&lt; std::distance(it1, it3) &lt;&lt; std::endl;

    return 0;
}

explain

  • std::distance(it1, it2):returnit1arriveit2The number of elements between them.
  • it1It is pointing to the containervecThe iterator at the start position,it2It is pointing to the containervecThe iterator at the end position (i.e.())。
  • The return value is5,expressit1arriveit2There are 5 elements between them.

Sample output:

Distance between it1 and it2: 5
Distance from begin to it3: 2

Other Instructions:

Time complexitystd::distanceThe 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::listorstd::set),std::distanceIt may involve traversals one by one, so it is less efficient.

Summarize

std::distanceIt 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!