Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand std::distance in C++

Tags:

c++

The code is as follow:

int B[] = {3,5};
int C[] = {4,5};
cout << distance(B,C);

The output is:

-4

Can anyone explain why is this?

like image 348
Euler Avatar asked Oct 10 '14 05:10

Euler


People also ask

What is std :: distance?

What is std :: distance? The std::distance() is an in-built function provided in the Standard Library (STL). The std::distance() method is used to find the distance between two iterators. It takes two iterators as arguments and returns an integer.

What type does std :: distance return?

std::distance Returns the number of elements between first and last . The behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first .

How do you find the distance between iterators?

If we have two iterators and we want to find the total no. of elements between the two iterators, then that is facilitated by std::distance(), defined inside the header file .


2 Answers

The distance(first, last) function tells you how many items are between the iterator at first and last. Note that pointers are iterators, random-access iterators to be specific. So the distance between one pointer and another is their difference, as defined by operator-.

So your question boils down to "How many ints are there between the int pointed to by B and the int pointed to by C?

distance dutifully subtracts the pointers and tells you.

The trick is that distance is supposed to be applied to iterators from the same container. Your code does not live up to that promise. The compiler is free to place the B and C arrays wherever it pleases, hence the result you see is meaningless. Like many things in C++, it's up to you to ensure that you're using distance properly. If you don't, you'll get undefined behavior, where the language makes no guarantees what will happen.

like image 171
Adam Avatar answered Sep 26 '22 04:09

Adam


std::distance(__first, __last) is designed to generalize pointer arithmetic, it returns a value n such that __first + n = __last.
for your case, the arguments are pointers of int*, in terms of iteration, they are random accessed iterators. the implementation simply returns a value of __last - __first:
simply (int*)C - (int*)B.

like image 22
Peixu Zhu Avatar answered Sep 22 '22 04:09

Peixu Zhu