How to understand std :: distance in C ++

The code looks like this:

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




Can someone explain why this is?


source to share

2 answers

The function distance(first, last)

tells you how many elements are between the iterator in first

and last

. Note that pointers are iterators, random access iterators to be specific. Thus, the distance between one pointer and another is the difference, as defined operator-


So your question boils down to "How much is ints

there between int

, which points to B

, and int

which points to C



dutifully subtracts pointers and tells you.

The trick is what is distance

supposed to be applied to iterators from the same container. Your code doesn't live up to this promise. The compiler is free to place the arrays B

and C

wherever you like, so the result is that you see, does not make sense. Like many other things in C ++, you have to make sure you are using it distance

correctly. If you don't, you will end up with undefined behavior, where the language does not guarantee what will happen.



std::distance(__first, __last)

is intended to generalize pointer arithmetic, it returns a value n

such that __first + n = __last

. For your case, the arguments are pointers int*

, in terms of iteration they are random access iterators. the implementation just returns the value __last - __first

simple (int*)C - (int*)B




All Articles