Multidimensional Vectors in STL


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:

image from book

 vector< vector<double> > vector1; 

image from book

If you would check vector1.size( ), you would find that the size of this vector is 0.

Another example would be:

image from book

 short ROWS = 4; short COLUMNS = 5; vector< vector<double> > vector2(ROWS, vector<double>(COLUMNS, 2.1); 

image from book

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:

image from book

 vector2[n][m] += (n + m); 

image from book

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.




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net