Intermediate Business Programming with C++
When we studied arrays, we saw that a multidimensional array was just an array of arrays. In a similar case, the multidimensional vector is just a vector whose elements are themselves vectors. For example the following would create a two dimensional vector of type double:
vector< vector<double> > vector1;
If you would check vector1.size( ), you would find that the size of this vector is 0.
Another example would be:
short ROWS = 4; short COLUMNS = 5; vector< vector<double> > vector2(ROWS, vector<double>(COLUMNS, 2.1);
This would create the vector2 that would be similar to a table which has 4 rows and 5 columns. If you would check vector2.size(), it will return 4 because there are 4 rows. To find the size of a column we would need to look at vector2[n].size() where 0 <= n < 5. To view the contents of each element, you would have to view: vector2[n][m]. To see an example of these concepts look at: multi1.cpp.
It is possible to change each element of a multidimensional vector by using the overloaded operator [ ] for each dimension. For example see: multi2.cpp where each element is changed as in the following:
vector2[n][m] += (n + m);
While multidimensional arrays are rectangular, multidimensional vectors may have each column with a different number of elements in it. Using push_back( ), additional columns can be added to a multidimensional vector. For an example, see: multi4.cpp. But that example only added more columns. It is also possible that some columns could have an additional element added using push_back( ) as well. For an example, see: multi3.cpp.
Категории