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.
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.
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:
To update the value, you can assign the value directly:
You can access all values with a nested loop and the size function for vectors.
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.
Last updated