Multidimensional arrays as class member with arbitrary bounds

烂漫一生 提交于 2019-12-13 07:15:39

问题


Not a duplicate of C++: multidimensional array initialization in constructor since the answers all appear to assume the bounds are known at compile-time.

I'm making a weighted undirected graph class arraygraph, backed by a 2D array of int, by the name of edges[][]. At instantiation time I don't really care what edges[][] holds; arraygraph has a method that reads a graph from a given filename and edges is set to a new int[n][n] (where n is the # of nodes in the file) by that function before it populates it.

Trouble is, g++ doesn't seem to like the way I've defined edges[][]. It wants to have set bounds for the array, and at compile time I don't know the bounds. Should I just redefine edges as an int *? Or as edges[][0]? Or something else entirely?

I'm not a C++ expert by any means (I'm a Python kinda guy) so complex, heavyweight options like the ones in Array with undefined size as Class-member are kinda out of scope (surely there's a simpler way than that...). If what I'm trying to do is a wrong thing entirely than that's also a useful thing to know, and it'd be handy to know what I ought to be doing instead.


回答1:


C++ doesn't know variable length arrays. So you need to define your array with a constant size. It's not possible either to redefine an array.

Two options for your multidimensional array:

  • dynamic array of arrays, implemented as int **edges
  • std::vector instead aka vector<vector<int>> edges;

vectors are extremely handy if you need to copy your data (done in a single statement), or change the sizes. So I'd recommend the second option :

int N=10; // dynamic! 
vector<vector<int>> m(N, vector<int>(N));

The alterative for using the pointer would be:

int N=10; // dynamic! 
int**m = new int*[N];    // allocate the first array 
for (int i = 0; i < N; i++) {  // allocate the second arrays
    m[i] = new int[N]{};
}

In both case, you'd access the data with the same syntax:

for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++)
        cout << m[i][j] << "\t";
    cout << endl;
}



回答2:


It seems you are looking for sort of dynamic size array. Try using std::vector instead of the array.



来源:https://stackoverflow.com/questions/29310863/multidimensional-arrays-as-class-member-with-arbitrary-bounds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!