4.1.2 The 2D Vector

2D Vectors

Declaring a 2D Vector

A 2D vector is essentially a vector of vectors. Creating a 2D vector, therefore, is similar to creating a standard vector, with the exception that the vector type is a vector itself.

// 2D vector is a vector of a vector
vector<vector<int> > nums;

In the example above, notice the space between the two closing angled brackets, >. Remember that two angled brackets together (>>) are used for streaming, so to distinguish the closing brackets from a streaming operator, you must leave a space between the two closing brackets.

Defining a 2D Vector with Default Values

Just like a single vector, you can create a 2D vector with default values. As a vector of vectors, you define the default values with sets of curly brackets, comma-separated.

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

Accessing and Updating Values

Similar to how you access a single vector, a 2D vector is accessed by stacking 2 sets of square brackets. The first bracket designated the row to access and the second bracket accesses the column. As always, the index values of the vectors start at zero and go to one less than the length of the vector.

In the example 2D vector above, to print the 3 in the third column of the first row, you would access it like this:

cout << nums[0][2] << endl;

To update the value, you can assign the value directly:

nums[0][2] = 8;

You can access all values with a nested loop and the size function for vectors.

for (int row = 0; row < nums.size(); row ++){
    for (int col = 0; col < nums[row].size(); col ++){
        cout << nums[row][col] << "\t";
    }
    cout << endl;
}

Adding to a 2D Vector

Just like with a 2D, you can use the push_back function to add to a vector. In the next example, you will look at adding rows, but to add a column to an existing row, you can do this by pushing back a value in the specified row.

nums[0].push_back(4); // Add to first row
nums[1].push_back(8); // Add to second row

Last updated