#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?
怪我咯2017-04-17 15:29:32
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.
大家讲道理2017-04-17 15:29:32
std::distance
returns not the number of bytes between d
and c
, but the number of d
s between c
and 元素
. The 元素
here refers to The type c
to which d
and int
belong.
Because int
is of size 4 bytes
, so 元素个数 = (C - 0) / 4 = 3
大家讲道理2017-04-17 15:29:32
c和d的值是00FDF7EC 00FDF7E0
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
std::distance(d, c)求出的值是3
sizeof(int) 为 4
12 / 4 = 3
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