Simple Deque initialization question
I have used the following code to insert some data in a deque.
int data[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
deque<int> rawData (data, data + sizeof(data) / sizeof(int));
But I dont understand this part of the code,
data + sizeof(data) / sizeof(int)
开发者_JAVA技巧
What does it mean?
Let's take that bit by bit.
data
is the iterator showing where to start. It's an array, but in C and C++ arrays decay to pointers on any provocation, so it's used as a pointer. Start taking in data from data
on, and continue until the end iterator.
The end iterator is a certain amount past the start iterator, so it can be expressed as data + <something>
, where <something>
is the length. The start iterator is an int []
that is treated as an int *
, so we want to find the length in int
s. (In C and C++, pointers increment by the length of the pointed-to type.)
Therefore, sizeof(data) / sizeof(int)
should be the length of the array. sizeof(data)
is the total size of the array in bytes. (This is one of the differences between arrays and pointers: arrays have a defined size, while pointers point to what might be the start of an array of unknown size.) sizeof(int)
is the total size of an int in bytes, and so the quotient is the total size of array
in int
s.
We want the size of array
in int
s because array
decays into an int *
, and so data + x
points to the memory location x int
s past data
. From a beginning and a total size, we find the end of data
, and so we copy everything in data
from the beginning to the end.
That's a pointer to the imaginary element beyond the last element of the array. The sizeof(data)/sizeof(data[0])
yields the number of elements in data
array. deque
constructor accepts "iterator to the first element" and "iterator beyond the last element" (that's what end()
iterator yields). This construct effectively computes the same as what .end()
iterator would yield.
精彩评论