Search code examples
c++arraysmultidimensional-arraystdvector

How can I initialize an array in C++ with a size that is given to the constructor?


I have a C++ class with a member that is supposed to be a two dimensional array. I want to declare my array as a member in the header file of the class. Then in the constructor of my class I want to initialize my array with a size (given to the constructor) and fill it with zeros.

I have a working example of what I want in java:

class Obj {
    int[][] array;
    public Obj(int sizex, int sizey) {
        array = new int[sizex][sizey];
    }
}

public class Main
{
    public static void main(String[] args) {
        Obj o = new Obj(12,20);
    }
}

I do not want to mess with pointers or alloc() and free(). As my class is supposed to be basically a wrapper for this array, I want to keep it simple.

I have thought about using std::vector, but as the array is never being resized after its initialization, I feel like vector is a little overpowered... Is there a better way than this: ?

#include<vector>

class Obj {
    std::vector<std::vector<int>> array;
    public:
    Obj(int xsize, int ysize) {
        std::vector<std::vector<int>> newArray(xsize, std::vector<int>(ysize, 0));
        array = newArray;
    }
};

int main()
{
    Obj o(12,20);
}

Solution

  • std::vector is the best match here. (As you said, in most cases raw arrays and pointers could be avoided. Also see How can I efficiently select a Standard Library container in C++11?)

    And you can initialize the data member directly in member initializer list instead of assigning in the constructor body after default-initialization, e.g.

    Obj(int xsize, int ysize) : array(xsize, std::vector<int>(ysize, 0)) {
    }