Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructing vectors from arrays

Tags:

c++

stdvector

This states I can construct a vector from an array as follows:

// the iterator constructor can be used to construct from arrays:
int myints[] = {16,2,77,29};
vector<int> myvector (myints, myints + sizeof(myints) / sizeof(int) );

Why is the constructor's second argument myints + sizeof(myints) / sizeof(int)?

like image 787
Alexey Avatar asked Sep 26 '12 20:09

Alexey


2 Answers

The expression sizeof(myints) / sizeof(int) gets the number of elements in the myints array.

myints gets a pointer to the first element of the array.

So the expression myints + sizeof(myints) / sizeof(int) is a pointer one past the end of the myints array, which is what the two-iterator constructor of std::vector expects. This creates a vector with a copy of all the elements in the original array.

Bear in mind that pointers are iterators, so the above is equivalent to

vector<int> myvector (std::begin(myints), std::end(myint));
like image 156
juanchopanza Avatar answered Sep 28 '22 09:09

juanchopanza


It gets pointer to an int after last element. So it becomes like begin() and end()

like image 28
PSIAlt Avatar answered Sep 28 '22 08:09

PSIAlt