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)
?
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));
It gets pointer to an int after last element. So it becomes like begin() and end()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With