I just started learning C++. I was trying to grasp the syntax for multidimensional arrays and vectors when I started to get fairly confused. I get how to initialize multidimensional arrays. It seems straightforward: Rows followed by columns. However, vectors are a little more challenging. Do I have to initialize them in the same way or do I create a vector of vectors. Somebody please help.
问题:
回答1:
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 a1
, a1[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.
回答2:
declare a multidimensional vector:
vector<vector<int> > test(4,vector<int>(20));
This creates a 2D vector 4 X 20. Of course since they're vectors that can be changed as needed. The indexing is the same as an array test[3][19]
.