Section 14.1 Multidimensional vectors
Vectors can be thought of as one dimensional storage. They represent a straight line of data, where there is one index used to locate each element.
Multidimensional storage is storage that requires 2 or more indexes to specify an element.
In C++, we can create multidimensional storage by making a vector that contains vectors. By convention, we think of the main vector as holding the horizontal rows of data. So to store the data shown in the figure above, we need to make a vector that contains three rows:
vector<??type??> table(3, ??value??);
But what type does the vector hold? And what value should be used as the starting value for each row? Well, each row holds a list of numbers - a
vector<int>
. And we want to start each of those rows as a vector that contains 5 copies of 0. (We will add the real data later).
// A row of 5 integers, all initialized to 0
vector<int> row(5, 0);
// A table that has three copies of row
vector<vector<int>> table(3, row);
table
itself is a vector with three elements. Each of those elements is a vector. Although we are trying to represent 2-dimensional storage, what we have is really a 1-dimensional list in which each value is a 1-dimensional list.
table
If we want to initialize the vector with particular values, we can do so using a list initializer that contains a list of lists:
vector<vector<int>> table = {
{6, 3, 2, 5, 7},
{11, 1, 4, 5, 8},
{7, 2, 6, 5, 3}
};
This would make the 3 row, 5 column table of data shown at the top of the page. Note that the outer
{...}
surround a list of three things separated by ,
. Each of those three things is a list of 5 items that are in {...}
and separated by a comma. (The newlines to space out the data more like how we picture it in the table are optional. The initialization could be on one long line.)
You have attempted of activities on this page.