Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Deque initialization question

Tags:

c++

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)

What does it mean?

like image 650
Quazi Irfan Avatar asked Nov 22 '25 07:11

Quazi Irfan


1 Answers

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 ints. (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 ints.

We want the size of array in ints because array decays into an int *, and so data + x points to the memory location x ints 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.

like image 200
David Thornley Avatar answered Nov 23 '25 21:11

David Thornley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!