Trying to make vector from part(5 elements) of c-array.
const static int size = 10;
cout << "vector from C-array: " << endl;
int ia[size] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
vector<int> vi2(ia, ia + size-5);
But when I try enumerate vector items using whole length of c-array I got all items like vector would be initialized like vector<int> vi2(ia, ia + size-5); . No exception or error that it goes out of range.
for(int i = 0; i < size; i++) {
cout << i << ":" << vi2[i] << " ";
}
In output:
0:1 1:2 2:3 3:4 4:5 5:6 6:7 7:8 8:9 9:10
Why vector initialization is using second param that describes pointer to array end if it doesn't uses it?
vi2.size()? It should give5, and if it does, accessing beyond the 5th element will give you undefined behaviour.vi2is using that end of array pointer. You are the one who is ignoring it and indexing it all the way tosize.vector<T>::at()instead ofvector<T>::operator[].\vector<int> vi2(ia, ia + 5);instead ofvector<int> vi2(ia, ia + size-5);. In this case, it doesn't matter, because size-5 == 5, but the first way indicates that you want the first five, and the second indicates you want all but the last five.