int main() {
vector <int> multiples(1);
cout << multiples[0];
}
This returns 0 when I want it to be 1. This happens when I initialize the vector with one element, I can access the second element, however:
int main() {
vector <int> multiples(1, 4);
cout << multiples[1]; // 4
}
Moreover, when I try to access elements in the vector that do not exist, I get the value of the rightmost element (in this case, 4). But I cannot seem to get the first element however. Can anyone explain why?
This
creates a vector of int with size 1. The single element is value initialized, which for
ìntmeans zero initialized. So you get a vector with one entry, with value0. And this onecreates a vector of size 1, this time with value
4. If you try to accessmultiplies[1]you are going beyond the bounds of your size-1 vector, thereby invoking undefined behaviour. It you want to initialize a vector with two elements of values1and4, in C++11 you can do this: