2D vectors

Explanation of the Code

First, the line

vector < vector <int> > twodvector;

declares an empty two dimensional vector named twodvector. A couple of things to notice:

  • like with all variables in C++, you have to declare what type of values will go into the vector. In this case, integers will go into the twodvector variable.

  • Notice the spaces between brackets < vector <int> >. Your program probably won't run if the spacing is not done correctly.

Then a one dimensional vector called singlerow is declared. The singlerow vector has the form [2, 2, 2].

vector<int> singlerow (3,2);

Then the singlerow vector is appended to the twodvector five times:

    for (int i = 0; i < 5; i++) {
        twodvector.push_back(singlerow);
    }

You end up with the same two-dimensional structure just like in the Python code. If you were to run this C++ code, the terminal would print out:

2 2 2 
2 2 2 
2 2 2 
2 2 2 
2 2 2 

Alternative Initialization

Here is another way you could have set up the vector from the previous example:

vector < vector <int> > twodvector (5, vector <int> (3, 2));

The syntax is a little bit more complicated. But if you start from the inside of the parenthesis and work your way out, you see that you have already seen all of the functionality.

The line:

vector <int> (3, 2) 

would set up an integer vector like {2, 2, 2}. So even though you don't see the inner vector, the code is essentially doing something like this:

vector < vector <int> > twodvector (5, {2, 2, 2});

So then the code copies {2, 2, 2} five times into the twodvector variable:

{{2, 2, 2},
{2, 2, 2},
{2, 2, 2},
{2, 2, 2},
{2, 2, 2}}

Just keep in mind that only Python represents vectors or matrices with square brackets []. Newer versions of C++ can use squiggly brackets to represent vectors {}, but older implementations of C++ do not have an equivalent representation.

A line of code like the following would not run in C++:

vector < vector <int> > twodvector (5, [2, 2, 2]);

Last updated