C ++将动态大小的2D数组传递给函数

时间:2010-12-13 23:10:56

标签: c++ arrays

我正在试图弄清楚如何传递2D数组,它是动态构造的一个函数。 我知道必须指定列数,但我的情况则取决于用户输入。

有没有解决方法?

示例:

// 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);

你明白了这一点:)

9 个答案:

答案 0 :(得分:4)

如果你使用的是C ++,那么合理的选择是:

  • 使用boost::multi_array (推荐)或
  • 制作自己的2D数组类。好吧,你不必这么做,但是在一个类中封装二维数组逻辑很有用,并使代码干净。

手动2D数组索引如下所示:

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

但是说真的,无论是用课程包装还是享受Boost已经为你准备好了这门课程。手动索引这个很烦人,使代码更不干净,容易出错。


修改

http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html说C99还有一个解决方案:

void func(int len, int array[len][len]) {
   // notice how the first parameter is used in the definition of second parameter
}

也应该在C ++编译器中工作,但我从未使用过这种方法。

答案 1 :(得分:1)

在C ++中,编译器可以计算出大小,因为它是类型的一部分。但不适用于动态大小的矩阵。

template<size_t N, size_t M>
void function(int (&matrix)[N][M])
{
  // do stuff
}

编辑:仅在GCC中,这是定义数组的代码所必需的,您可以直接传递可变长度数组:

void func(int N, int matrix[N][N])
{
  //do stuff
}

请参阅the gcc documentation

答案 2 :(得分:1)

/*******************************************************\
*                                                       *
* I am not claiming to be an expert, but I think I know *
* a solution to this one. Try using a Vector Container  *
* instead of an array. Here is an example below:        *
*                                                       *
* Load the target file with a Multiplication Table      *
*                                                       *
*                                                       *
\*******************************************************/

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
#include <vector>


std::string user_file;
int user_size = 2;
void array_maker(int user_size, std::string user_file);

int main () {
  std::cout << "Enter the name of the file for your data: ";
  std::cin >> user_file;
  std::cout << std::endl;
  std::cout << "Enter the size for your Multiplication Table: ";
  std::cin >> user_size;

  // Create the users Multiplication data
     array_maker(user_size, user_file);

  return (0);
}

void array_maker(int user_size, std::string user_file)
{
  // Open file to write data & add it to end of file
  std::ofstream target_file(user_file,std::ios::out | std::ios::app);

  // Declare the vector to use as a runtime sized array
  std::vector<std::vector<int>> main_array;

  // Initialize the size of the vector array
  main_array.resize(user_size+1); // Outer Dimension
  for (int i=0; i <= user_size; ++i) // Inner Dimension
  {
    main_array[i].resize(user_size+1);
  }

  for (int i=0; i<=user_size; ++i) 
  {
    for (int j=0; j<=user_size; ++j)
    {
      main_array[i][j] = i * j;
      // output line to current record in file
      target_file << i << "*" 
              << j << "=" 
              << main_array[i][j] << " "
              << "EOR"   // End of Record 
              << std::endl;

    } // Close Inner For
  } // Close Outer For
  // close file
  target_file.close();

} // Close array_maker function

答案 3 :(得分:0)

你可以做到 void function(int ** __ matrix,int32_t __row,int32_t __column) __row - 最大行数 __column - 最大列。

您将需要这些参数来找出数组的限制。

答案 4 :(得分:0)

只需在您的函数中添加其他参数 - row_numbercolumn_number即可。数组在C ++中不是对象,因此它们不存储关于它们的任何其他信息。

答案 5 :(得分:0)

如果传入数组标识符(作为指针指针),则需要使用指针算法:

void function(int** matrix, int num_rows, int num_cols) {
    Assert(matrix!=NULL && *matrix!=NULL && num_rows>0 && num_cols>0);

    for(int i=0; i<num_rows; i++) {
        for(int j=0; j<num_cols; j++) {
            // cannot index using [] like matrix[i][j]
            // use pointer arithmetic instead like:
            // *(matrix + i*num_cols + j)

        }
    }
}

答案 6 :(得分:0)

将多维数组传递给方法,编译器需要知道每个字段的深度,因此一种解决方案是以正常方式使用模板和调用方法,编译器将猜测每个字段的大小。

template <size_t m>
void method(int M[][m])
{
    for(int i=0; i<m; ++i)
        for(int j=0; j<m; ++j)
        {
            // do funny stuff with M[i][j]
        }
}

int main()
{
    int M[5][5] = { {1,0,1,1,0}, {0,1,1,1,0}, {1,1,1,1,1}, {1,0,1,1,1}, {1,1,1,1,1} };
    method(M);
    // also you can call with method<5>(M)
    // if you have different sizes for each dimension try passing them in args
    return 0;
}

答案 7 :(得分:-1)

int r, c
int *matrix = new int[r,c];
for (int i = 0; i < r; i++)
    {
        /*cout << "Enter data" << endl;*/
        for (int j = 0; j < c; j++)
        {
            cin >> matrix[i,j];

        }
    }

答案 8 :(得分:-3)

void function(int&amp; matrix [] [])

相关问题