VOOZH about

URL: https://www.geeksforgeeks.org/cpp/stddistance-in-c/

⇱ std::distance in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

std::distance in C++

Last Updated : 28 Oct, 2024

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:


Output
5

std::distance() Syntax

std::distance(first, last);

Parameters

  • first: Iterator/pointer to the first element of the given range.
  • last: Iterator/pointer to the element just after the last element of the given range.

Return Value

  • Returns the number of elements between the two iterators. If first comes before last, the result is positive; otherwise, it is negative.

Working of std::distance()

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).

More Examples of std::distance()

The following examples demonstrates the use of std::distance() function in different scenarios:

Example 1: Finding Number of Elements in a Part of Vector


Output
4

Time Complexity: O(1)
Auxiliary Space: O(1)

Example 2: Finding the Number of Elements in an Array


Output
5

Time Complexity: O(1)
Auxiliary Space: O(1)

Example 3: Finding the Number of Elements in a Part of List


Output
4

Time Complexity: O(n), where n is the number of elements between the two iterators of std::set.
Auxiliary Space: O(1)

Example 4: Negative Distance


Output
-5

Example 5: Passing Iterators of Different Containers to std::distance()


Output
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.

Comment