Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

distance
c++
communitycreator

What is the distance() function in C++?

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The distance() function in C++ helps find the distance between two iterators. In other words, we can use this function to calculate the number of elements present between the two iterators. This function is available in the <iterator> header file.

Parameters

The distance() function accepts the following parameters.

  • first: This is an iterator that points to the initial position of the array or vector.

  • last: This is an iterator that points to the last position of the array or vector.

Return

The distance() function returns the number of elements between first and last.

Code

Let’s look at the code now.

#include <iostream>
#include <vector>
#include <list>
using namespace std;

int main () {
  vector<int> vec = {1,2,3,4,5,6,7,8,9,10};

  int dist = distance(vec.begin(), vec.end());

  cout << "The distance is: " << dist;

  return 0;
}
Use distance() function in C++

Explanation

  • From lines 1 to 3, we import the required header files.
  • In line 7, we create a vector that contains some integer values.
  • In line 9, we call the distance() function and pass the two iterators.
  • In line 11, we print the number of elements present between the two iterators.

RELATED TAGS

distance
c++
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring