Multidimensional Vectors in C++

If you are able to use C++11, multidimensional arrays and vectors of vectors can be initialized in a similar manner.

int a1[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
std::vector<std::vector<int>> a2 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

However, there are differences that must be understood to access the elements without running into undefined behavior.

For a multidimensional array, memory for the elements of the array is required to be allocated contiguously. For a vector of vector, the memory for the elements is most likely going to be disjoint.

Memory for a1:

a1[0][0]    a1[1][0]    a1[2][0]
|           |           |
v           v           v
+---+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+

Memory for a2 (most likely):

a2[0][0]
|
v
+---+---+---+
|   |   |   |
+---+---+---+

a2[1][0]
|
v
+---+---+---+
|   |   |   |
+---+---+---+

a2[2][0]
|
v
+---+---+---+
|   |   |   |
+---+---+---+

Also, it is possible to defined a vector of vectors in which the number of columns is not same for each row.

std::vector<std::vector<int>> a2 = { {1, 2, 3}, {4, 5}, {6, 7, 8, 9} };

In a multidimensional array, the number of columns is guaranteed to be same for each row.

Given the above multidimensional array a1a1[1][2] will be a valid element and a1[2][3] will be an invalid element. In the case of a vector of vectors, using the above line, a2[1][2] is not a valid element and a2[2][3] is a valid element.

Leave a Comment

error code: 523