简体   繁体   English

如何使用给定构造函数的大小初始化 C++ 中的数组?

[英]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.我有一个 C++ class 和一个应该是二维数组的成员。 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.我想将我的数组声明为 class 的 header 文件中的成员。然后在我的 class 的构造函数中,我想用一个大小(给构造函数)初始化我的数组并用零填充它。

I have a working example of what I want in java:我在 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().我不想弄乱指针或 alloc() 和 free()。 As my class is supposed to be basically a wrapper for this array, I want to keep it simple.因为我的 class 基本上应该是这个数组的包装器,所以我想保持简单。

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: ?我考虑过使用 std::vector,但由于数组在初始化后从未调整过大小,我觉得 vector 有点过于强大了……有没有比这更好的方法:?

#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);
}

std::vector is the best match here. std::vector是这里的最佳匹配。 (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? ) (正如您所说,在大多数情况下,可以避免使用原始 arrays 和指针。另请参阅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, eg您可以直接在成员初始化列表中初始化数据成员,而不是在默认初始化后在构造函数体中分配,例如

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

Other than using std::vector you can just allocate memory of the required size from the heap.除了使用 std::vector 之外,您只需从堆中分配所需大小的 memory。

class Obj {
    int** arr;
    int x, y;
public:
    Obj(int sizex, int sizey) : x(sizex), y(sizey) {
        arr = new int*[sizex];
        for (unsigned i = 0; i < sizex; i++) {
            arr[i] = new int[sizey];
        }
    }

    //IMPORTANT TO DELETE, OTHERWISE YOU'LL GET A MEMORY LEAK
    ~Obj() {
        for (unsigned i = 0; i < x; i++) {
            delete[] arr[i];
        }
        delete[] arr;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM