本文介绍了C++ 将动态大小的二维数组传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何将动态构造的二维数组传递给函数.我知道必须指定列数,但就我而言,这取决于用户输入.

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(推荐),或
  • 制作您自己的二维数组类.好吧,您不必这样做,但在类中封装二维数组逻辑很有用,并且可以使代码变得干净.

手动二维数组索引如下所示:

Manual 2D array indexing would look like this:

void func(int* arrayData, int arrayWidth) {
    // element (x,y) is under arrayData[x + y*arrayWidth]
}

但是说真的,要么用一个类来包装它,要么享受 Boost 已经为您准备好了该类.手动索引这个很烦人,而且会使代码更不干净,更容易出错.

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++ 将动态大小的二维数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-21 10:19