#include <iostream>
#include <iterator>
int main()
{
int a, b;
int *c = &a, *d = &b;
std::cout << std::hex << c << " " << d << std::endl;
std::cout << std::hex << std::distance(d, c) << std::endl;
return 0;
}
我运行时显示
c和d的值是00FDF7EC 00FDF7E0
std::distance(d, c)求出的值是3
可是他们地址相差不是C么,为什么是3?
std::distance returns the distance of the iterator, not the difference in addresses.
For example, you can also use std::distance(list::begin(),list::end()) to calculate the number of ++ between two iterators in the linked list, and we know that the addresses of the linked list are not in order Emissions.
The pointer c above also reaches the position of d after ++ three times. The ++ of int* moves sizeof(int) every time.
Generally speaking, the implementation of distance is to ++ move the iterator in the for loop and then compare to record the distance between them.
std::distance
returns not the number of bytes betweend
andc
, but the number ofd
s betweenc
and元素
. The元素
here refers to The typec
to whichd
andint
belong.Because
int
is of size4 bytes
, so元素个数 = (C - 0) / 4 = 3
c is the pointer to a, at the high address on the stack
d is the pointer to b, at the low address on the stack
The difference between c and d is 12 bytes, and 12 bytes are the bytes occupied by the size of 3 int types
So the distance between c and d is 3 int type size bytes
The distance the pointer moves in addition and subtraction is the size of the type pointed by the pointer
The pointer addition and subtraction in this problem results in the number of ints (four bytes), and pointers do not perform bit operations