Search code examples
c++dynamic-memory-allocation

How to declare a 2D vector parameter which will accept any size?


I've just started to learn C++.

I have to declare a method that will accept variables like this ones:

int grid1[200][200];
int grid2[20][25];
int grid3[53][40];

How do I have to declare that parameter in the method?

I have found this declaration, but I don't know if it is useful or how can I use it:

int** a = new int*[rowCount];

I will copy that parameter to a member variable that will be dynamic (I think it will be in the heap, so this is why it is dynamic).


Solution

  • For statically sized arrays, use std::array. For dynamically sized arrays use std::vector. Don't ever use raw C arrays unless some weird situation forces it on you.

    If you need a multi dimensional array, you can of course use std::vector<std::vector<int>> or similar for std::array. This is easy and convenient since you can do myarray[row][column] (and possibly good enough). But a better performing option is usually to just declare a 1D std::vector<int> with a size of "dimension 1 * dimension 2" and then, when indexing into it, do myvector[row_number * size_of_row + column]. Treating a 1D array as a 2D one is as easy as that and it is likely to perform better since it's friendlier to your CPUs prefetcher and cache hierarchy.

    As for declaring a function to accept such arrays - it's straight forward. For example:

    void f(const std::array<int, 666>& myarray);
    void f(const std::array<std::array<int, 42>, 666>& myarray);
    void f(const std::vector<int>& myarray);
    void f(const std::vector<std::vector<int>>& myarray);