Reputation: 1740
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?
Upvotes: 9
Views: 57087
Reputation: 4129
For interested readers, Boost has a MultiArray library designed specifically for this problem. It claims to be more efficient than std::vector<std::vector<...>>
and its interface is C++ STL friendly.
#include "boost/multi_array.hpp"
int main () {
// Create a 3D array that is 3 x 4 x 2
boost::multi_array<double, 3> A(boost::extents[3][4][2]);
// Assignment
A[0][0][0] = 1.0;
// Dereference
std::cout<<A[0][0][0];
return 0;
}
Read more here
Upvotes: 6
Reputation: 6958
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]
.
Upvotes: 23
Reputation: 206717
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.
Upvotes: 21