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?
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.
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 .
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 .
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With