Since vectors are preferred to arrays in C++, I would like to ask what kind of structure you suggest generally in case one wants to store data in a multidimensional array form (m rows, n columns). Vector of vectors is a reasonable and effective practice?
-
Yes. Not sure what else to say. – Brian Roach Dec 07 '11 at 07:09
-
possible duplicate of [Multi-Dimensional Array ( C++ )](http://stackoverflow.com/questions/741190/multi-dimensional-array-c) – Greg Hewgill Dec 07 '11 at 07:11
3 Answers
Yes, vector of vectors is an reasonable practice. Why do you think its not?
Effective depends on whether you know the number of elelemts in advance.
If not then you cannot have Variable length arrays in C++ anyways so vector is an good option.
With C++11 std::array
is also a good option.

- 202,538
- 53
- 430
- 533
There's nothing at all wrong with having an std::vector< std::vector<int> > matrix
.
However, if the size of your multi-dimensional structure is going to be fixed (ie m by n) and you don't need the extra functionality provided by std::vector
, then perhaps an std::array
is a good alternative.

- 18,014
- 6
- 40
- 44
-
-
@WTP: It is in C++11. AFAIK Clang and the yet-to-be-released GCC 4.7 support them. – R. Martinho Fernandes Dec 07 '11 at 07:21
-
@WTP: Even if it is possible, do you think doing so would be a help or a hindrance? I know I'd personally prefer not to `typedef` it. – AusCBloke Dec 07 '11 at 07:43
Depends of what you want to achieve. vector of vectors can be used, but you may also have one unique array/vector and compute the index when you want to access elements with the formula row + row_size * column... Using vectors may use more memory than you need, so if your matrix is very huge, this may not be the best solution.
If you work with numerics, you may also have a look to boost::uBLAS which is a matrix library with many possible storage policies (matrix by row, by column, compressed, triangular...) - each of the proposed matrix model fits a particular problem to have best performances or limit allocated memory.
I think you should study all the possible methods of storage and chose the one which will best fit your problem.

- 2,706
- 1
- 15
- 22