4.1.3 Creating a 2D Vector

Creating 2D Vectors

As you saw in the last example, you can create a 2D vector using default values with nested curly brackets.

vector<vector<int> > nums {{1, 2, 3},
                           {5, 6, 7}};

While this option may work for small grids, an automated process is critical for creating larger grids.

Creating 2D Vectors with Loops

Unlike a traditional array, the structure of a vector is not fully developed when it is declared. Declaring a 2D vector does not provide a place to update values that have not been pushed back into the vector structure.

Here is an example of the problem:

vector<vector<string> > words; // Defines 2D vector
words[8][6] = "Hello"; // Will fail

In the example above, the code will fail since the word grid doesn’t yet have a row 8 or a column 6.

To remedy this, if you want to create a filled grid, you would need to loop through and add rows and columns to initialize the grid.

To do this, you first create a row by pushing back all the default column values, then you push the row back to the main grid.

Let’s look at an example where you create an empty 10 by 10 string grid.

vector<vector<string> > words;
for (int i = 0; i < 10; i++) {
    vector<string> row; // Create a row
    for (int j = 0; j < 10; j++) {
        row.push_back(""); // Add default column
    }
    words.push_back(row); // Add row to grid
}

After running the nested loop above, you will be left with an empty structure that can then be updated using square brackets to access values.

words[8][6] = "Hello"; // Will now work

Last updated