Ranges in C++ are specified in the form
[first, last)
The closing parenthesis instead of square bracket means that acceptable values do not include the value last
.
Thus in this declaration
vector<int> b(&a[0], &a[5]);
the acceptable range of pointers (iterators) is [&a[0], &a[5] )
that is the value pointed to by the pointer &a[5]
will not be used in the initialization of the vector b
. The vector will have only 5 elements equal to a[0], a[1], a[2], a[3] and a[4]
.
So using the magic number 6 in this loop
for (int i = 0; i < 6; i++) {
cout << b[i] << endl;
}
results in undefined behavior.
You could write for example
for ( size_t i = 0; i < b.size(); i++ )
{
std::cout << b[i] << std::endl;
}
or just
for ( auto x : v ) std::cout << x << std::endl;
It is evidently that it would be simpler to initialize the vector b like
vector<int> b( a );
But if you want to specify some range of the vector a
as an initializer of the vector b
then you can write for example
#include <iterator>
//...
vector<int> b( a.begin(), std::next( a.begin(), 6 ) );