1

What is the difference between allocating a multidimensional array like this

double matrix[1000][2];

or like this

unsigned int cols = 2, rows = 1000;
std::vector<double> temp(cols, 0);
std::vector<std::vector<double>> matrix(rows, temp); 

In each case I can refer to elements using terms such as matrix[i][j]

I've seen both methods described on C++ tutorial pages. The first seems simpler, but I'm wondering whether there are any pitfalls that using the vector method would help me avoid.

I have a relatively small data set so am not too worried about dynamic allocation and .push_back / .resize, but will be creating and abandoning data often so don't want to have any memory leak problems.

underscore_d
  • 6,309
  • 3
  • 38
  • 64
Sir Adelaide
  • 119
  • 3
  • 2
    How about `std::array`? – Ed Heal Apr 05 '18 at 13:45
  • 2
    Agreed if you are not resizing the array `std::array` is a better choice. – drescherjm Apr 05 '18 at 13:46
  • The exact same pitfalls that you may get if you use C arrays. – user202729 Apr 05 '18 at 13:48
  • 5
    `std::` or plain, an array on the stack will start giving you problems if your dimensions start getting larger - or, for all I know, some smaller platforms might not even like `[1000][2]` already. – underscore_d Apr 05 '18 at 13:49
  • You can use also matrix[i][j] notation with std::vector. In addition, using C-array obliges you to manage memory deallocation and to check element access boundary. If you allow exception, with accessor at() boundary check is done naturally and can raise an exception. If you know at compile-time how many elements you have in your matrix, use std::array(). – Ratah Apr 05 '18 at 14:00
  • 1
    There are two issues here. First is, if you don't need the functionality of a template, in this case vector & the ability to resize it, you should look for a simpler one. In this case, the alternative is std::array, which is a C array with some C++ STL functionality laid over it, e.g. iterators. Second is understanding what the template does. C arrays are allocated on the stack (quick, efficient, and limited by stack size), while vector's memory is assigned on the heap, which is more expensive. Vector of vectors is not likely to be continuous, which hurts locality & performance. – Uri Raz Apr 05 '18 at 14:03
  • One pitfall std::vector & std::array will save you is the at() member function which checks, at least in debug mode, for out of bounds errors. C arrays don't have that. – Uri Raz Apr 05 '18 at 14:06
  • @UriRaz `at()` always checks for out of bounds, not only in debug mode. – mch Apr 05 '18 at 14:17

0 Answers0