【问题标题】:How to use the same multidimensional array in many functions?如何在多个函数中使用相同的多维数组?
【发布时间】:2016-12-16 14:42:18
【问题描述】:

我是 C++ 的初学者,老实说,我不知道如何解决一项任务。 我必须使用二维数组创建一个矩阵。它的大小应该取决于用户的输入(它应该类似于...int matrix[m][n],其中 m 和 n 是用户输入的数字)。然后我应该用 0 到 100 的随机数填充它并打印它。嗯,我能应付。 当我必须创建一个从该数组的行中查找最大数字的函数时,问题就开始了。该函数的唯一参数可以是用户输入的行数(例如 int function(int i))。 问题是——如何在多个函数中使用同一个数组?考虑到我是新手,有什么办法可以做到这一点? 或者任务的形成不正确? 对不起,很长的帖子,并提前感谢 PS有人要代码,所以这里是:

#include <iostream>
#include <cstdlib>
using namespace std;
int function1(int i)
{
//this is one of the functions I'm supposed to create-I described it earlier
}
int main()
{
int m,n;
cout<<"Matrix's size will be m rows and n columns. Please write m and n"<<endl;
cin>>m>>n;
int A[m][n];
int a,b;
for (a=0;a<m;a++)
{
for (b=0;b<n;b++)
{
A[a][b]=rand()%(100+1);
    cout<<A[a][b]<<" ";
}
cout<<"\n";
}
}

编辑:我要感谢大家的帮助。我问过我的老师,他终于回答了。如果您好奇,他告诉我们(我没听说过)定义一个类似 int[100][100] 或更高的数组,并且不允许用户输入任何更高的数字;)这不是最佳解决方案,但肯定是实用的。再次感谢!

【问题讨论】:

  • 函数只有一个 int 参数的要求听起来很随意。这真的有必要吗?如果是,则只能将矩阵设为全局,但最好将其作为函数参数传递
  • 一定要用数组吗? std::vector 在这里可以很好地工作。
  • 嗯,根据上面写的,它应该看起来像 int 函数(int i),所以我想它应该只有一个参数——我还应该创建切换所选列的函数在那里,我必须将它作为函数参数传递。但是,如果在运行程序之前它的大小未知,我怎样才能使矩阵全局化? :)
  • 而且我必须使用数组,否则我肯定会使用 std::vector
  • 如果不能使用 STL,这在 C++ 中会很混乱。那么最好使用 C,因为它有 VLA。

标签: c++ arrays multidimensional-array


【解决方案1】:

在 C++ 中执行此操作的正确方法是使用 std::vector 或 std::array。

如果您因为人为要求而无法做到这一点,那么您根本无法声明基于用户输入的 C++ 中的二维数组。

cin >> m >> n;
...
int array [m][n];  // not possible
int** wannabe;     // not an array
int array [m * n]; // not possible

你可以做的是一个“错位”的二维数组:

int* mangled = new int[m * n];

使用示例:

class int_matrix
{
  private:
    int*   mangled;
    size_t rows;
    size_t cols;

  public:
    int_matrix(size_t row, size_t col)
      :rows(row),
       cols(col)
    {
      mangled = new int[row * col];
    }

    int highest_in_row (size_t row)
    {
      ...
    }
};

请注意,此代码要求您关注the rule of three


在 C 语言中,您可以通过编写 int array[m][n] 优雅地解决这个问题,但您使用的是 C++,所以您不能这样做。

【讨论】:

    【解决方案2】:

    您可以将您的函数包装到一个类中。在该类中,您可以将数组作为成员变量。

        class A { 
          int **matrix;
    
          public:
           A(int rows, int columns) {
            matrix = new int*[rows];
            for(int i = 0; i < rows; ++i)
              matrix[i] = new int[columns];
           }
    
       int function(int i); //you can use your matrix in this function
    }
    

    如果不能使用类,可以使用全局变量。

    在文件.cpp中

        int **matrix;
    
        int function(int i) {
           //Do Something
        }
    
    //With rows the number of rows and columns the number of columns
    //You can take these as parameters
        int main() {
           matrix = new int*[rows];
            for(int i = 0; i < rows; ++i)
              matrix[i] = new int[columns];
           function(42);
        }
    

    【讨论】:

    • 对不起,但它显示“'矩阵'的声明为多维数组必须对除第一个之外的所有维度都有边界|”
    • 这永远不会在 C++ 中编译。
    • 试试 int **matrix;并在构造函数中 matrix = new int*[rowCount]; for(int i = 0; i
    • @GodineauFélicie 你建议的不是二维数组,所以它没有帮助。
    • 如果是一维数组,据我所知不会有任何问题。所以感谢您指出这一点,它必须是二维数组。
    【解决方案3】:

    如果你声明一个像 int int A[m][n]; 这样的矩阵,其中 mn 不是 const,你不能将它传递给函数。有两种方法可以解决它:

    1) 声明具有 const 大小的矩阵,例如 int A[10][10];。在这种情况下,找到 max 的函数将如下所示:

    int max_in_row(int matr[10][10], int row) {
        int max = 0;
        for (int col = 0; col < 10; ++col)
            if (matr[row][col] > max)
                max = matr[row][col];
        return max;
    }
    

    你可以找到最简单的int max = max_in_row(A, &lt;row you want&gt;);

    2) (如果你不知道大小)将矩阵声明为数组数组:

    int **A = new int*[n];
    for (int i = 0; i < n; ++i)
        A[i] = new int[m];
    // fill A like you did
    

    那么函数会是这样的

    int max_in_row(int **matr, int row, int m) {
        int max = 0;
        for (int col = 0; col < m; ++col)
            if (matr[row][col] > max)
                max = matr[row][col];
        return max;
    }
    

    你可以通过int max = max_in_row(A, &lt;row you want&gt;, m);找到最大值

    【讨论】:

    • 为什么要使用指向指针的指针?仅此一点就表明您没有二维数组,而是其他东西。
    【解决方案4】:

    以下不是标准 C++,因为它仅在编译器支持可变长度数组时才有效。 VLA 是在 C99 中引入的,在 C11 中是可选的,但从未在 C++ 标准中引入 - 但有些编译器甚至在 C++ 模式下也支持它。

    黑客将矩阵地址存储为全局void *,并将其转换为函数内指向VLA的正确指针。这种 hack 是必需的,因为在全局声明时您无法知道矩阵的列数。

    #include <iostream>
    #include <cstdlib>
    
    void *Matrix;
    int Columns;
    
    using namespace std;
    int function1(int i)
    {
        typedef int MAT[Columns];   // BEWARE!!! VLA is not standard C++
        MAT *mat = static_cast<MAT *>(Matrix);
        int mx = mat[i][0];
        for(int j=0; j<Columns; j++) {
            cout << " " << mat[i][j];
            if (mat[i][j] > mx) mx = mat[i][j];
        }
        std::cout << endl;
        return mx;
    }
    int main()
    {
    int m,n;
    cout<<"Matrix's size will be m rows and n columns. Please write m and n"<<endl;
    cin>>m>>n;
    int A[m][n];         // BEWARE!!! VLA is not standard C++
    int a,b;
    for (a=0;a<m;a++)
    {
    for (b=0;b<n;b++)
    {
    A[a][b]=rand()%(100+1);  // Note that I now use a and b here !
        cout<<A[a][b]<<" ";
    }
    cout<<"\n";
    }
    Matrix = static_cast<void *>(A);
    Columns = n;
    
    cout << "Enter row number to process: ";
    cin >> a;
    b = function1(a);
    cout << "Max of row " << a << " is " << b << endl;
    return 0;
    }
    

    不是真正的 C++-ish,但至少它可以编译并使用 clang 版本 3.4.1 给出预期的结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 2020-02-05
      • 2019-10-14
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多