C ++通过动态调整大小的二维数组的功能 [英] C++ passing Dynamically-sized 2D Array to function
问题描述
我试图找出如何通过二维数组,这是动态构造函数。
我知道必须指定的列这个数字,但是我的情况下,这取决于用户的输入。
I'm trying to figure out how to pass 2D array, which is constructed dynamically to a function. I know that number of columns must be specified, but it my case it depends on user input.
是否有任何变通办法?
例如:
// Some function
void function(matrix[i][j]) {
// do stuff
}
// Main function
int N;
cout << "Size: ";
cin >> N;
int matrix[N][N];
for (int i=0;i<N;i++) { //
for (int j=0;j<N;j++) {
cin >> matrix[N][N];
}
}
sort(matrix);
您明白了吧:)
推荐答案
如果你在C ++中,合理的方案是:
If you're on C++, the reasonable options are to:
- 使用
的boost :: multi_array的
(推荐),或 - 请你自己的二维数组类。那么,你不必,但在封装类二维数组的逻辑是非常有用的,使code干净。
手册二维数组索引应该是这样的:
Manual 2D array indexing would look like this:
void func(int* arrayData, int arrayWidth) {
// element (x,y) is under arrayData[x + y*arrayWidth]
}
但严重的是,无论是与一类包装这或享受升压已经具有类为你准备好。手动索引,这是无聊的,使code的不洁且容易出错。
But seriously, either wrap this with a class or enjoy that Boost already has that class ready for you. Indexing this manually is tiresome and makes the code more unclean and error-prone.
修改
http://gcc.gnu.org/onlinedocs/gcc/Variable- Length.html 说,C99有你一个解决方案:
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html says that C99 has one more solution for you:
void func(int len, int array[len][len]) {
// notice how the first parameter is used in the definition of second parameter
}
还应该在C ++编译器的工作,但我还没有使用过这种方法。
Should also work in C++ compilers, but I haven't ever used this approach.
这篇关于C ++通过动态调整大小的二维数组的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!