-1
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?

David G
  • 94,763
  • 41
  • 167
  • 253
  • the 1 is how many elements it has, not the location of the index, the index location still starts at 0, like an array. – Rivasa Aug 12 '12 at 00:30
  • See this question for future support of the concept you are trying to use: http://stackoverflow.com/questions/2409819/c-constructor-initializer-for-arrays – Steve-o Aug 12 '12 at 00:38

4 Answers4

4

This

vector <int> multiples(1);

creates a vector of int with size 1. The single element is value initialized, which for ìnt means zero initialized. So you get a vector with one entry, with value 0. And this one

vector <int> multiples(1, 4);

creates a vector of size 1, this time with value4. If you try to access multiplies[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 values 1 and 4, in C++11 you can do this:

vector <int> multiples{1, 4};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1
int main() {

    vector <int> multiples(1);

    cout << multiples[0];

}

http://cplusplus.com/reference/stl/vector/vector/

creates vector with 1 int element, initialized by default (i.e. int() == 0).

vector <int> multiples(1, 4);

creates vector with 1 int element initialized by 4.

cout << multiples[1]; // 4

it's incorrect, since there only one element in vector.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
1

Take a look at this code. You should see the problem. You are not initializing the vector in the way that you expected.

int main()
{
    vector <int> multiples(2); // create a vector of size two with default value of 0.
    multiples[0] = 10; // set element at index 0 = 10
    multiples[1] = 20; // set element at index 0 = 10
    cout << multiples[0]; // 10
    cout << multiples[1]; // 20
}
kakridge
  • 2,153
  • 1
  • 17
  • 27
0

Actually, you dont need to specify the size of vector. You can add elements (objects to be specific) as and when you require, that is the main advantage and use of vectors. Adding an element to vector can be easily done by:

multiples.push_back(1);
multiples.push_back(4);

Hope it helps.

David G
  • 94,763
  • 41
  • 167
  • 253
Shash
  • 11
  • 3