2D Vectors push_back

Viewed 44

I'm trying to push_back numbers into a 2D vector that's composed of 1 row and 1 column.

    vector< vector <int>>array;
    array.push_back(vector<int>(3)); 
    array[0].push_back(2);
    cout << array[0][0] << endl;

I expected this to return 3, but it returns 0. Why's that?

1 Answers

vector<int>(3) creates a vector containing 3 elements with value 0.

  1. Constructs the container with count default-inserted instances of T. No copies are made.

If you want a vector containing 1 element with value 3, you can change to vector<int>{3}.

  1. Constructs the container with the contents of the initializer list init.

e.g.

array.push_back(vector<int>{3});
Related