'How to understand std::distance in 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?

c++


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1