1

For the following code, vv[1].size() will return an output of 4. I was wondering where this number came from.

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<vector<int>> vv;
    vector<int> v1(3,5);
    vector<int> v2(4,7);
    vv.push_back(v1);
    vv.push_back(v2);
    cout << vv.size() << endl << vv[1].size() << endl;
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Caitlyn T
  • 33
  • 2

1 Answers1

2

This is because vector<int> v2(4,7); creates a vector of size 4 whose values are all 7. You most likely meant to write vector<int> v2 {4,7}; which creates a vector with 2 elements of 4 and 7.

jeff544
  • 51
  • 2
  • 1
    [here](https://en.cppreference.com/w/cpp/container/vector/vector) you can find a complete list of constructors of `std::vector` – Aykhan Hagverdili Dec 08 '19 at 04:55
  • The code was actually a practice problem where I was supposed to write the output. I think I'm having trouble grasping `vector> vv` . Why is vv[1] v2? – Caitlyn T Dec 08 '19 at 04:57
  • 1
    Ah I see, that is because vv is a vector of vectors. "push_back" adds the vector you created to the vector of vectors. At the end of the program, vv will look like this: [[5, 5, 5],[7,7,7,7]]. [5,5,5] is the first vector created as v1, [7,7,7,7] is the second created as v2. – jeff544 Dec 08 '19 at 05:03
  • 1
    Size and number of elements are different. You can pre-allocate memory for a vector and show a rather lengthy size even though there are no valid elements within the vector. When you run over the Pre-alllocation amount, it typically increments in powers of two unless you change the re-size granularity for the data structure – Paul Renton Dec 08 '19 at 06:11