如何将未知大小的二维数组传递给函数 [英] How to pass two dimensional array of an unknown size to a function

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

问题描述

我想创建一个类库,一个函数,它的参数是一个未知大小的矩阵,用户将自己的大小创建自己的矩阵,并将其传递给这个函数,在这个矩阵上做一些操作,将是函数

  calculateDeterminantOfTheMatrix(int matrix [] [])
{
一些操作on matrix
}


解决方案

多维数组没有得到C和C ++内置组件的很好支持。只有在编译时知道 N-1 尺寸时,才可以传递 N -dimension数组:

  calculateDeterminantOfTheMatrix(int matrix [] [123])

然而,标准库提供了 std :: vector 容器,这对多维数组非常有效:在你的情况下, code>矢量<矢量< INT> > & matrix 是处理C ++任务的正确方法。

  int calculateDeterminantOfTheMatrix( vector< vector< int>>& matrix){
int res = 0;
for(int i = 0; i!= matrix.size(); i ++)
for(int j = 0; j!= matrix [i] .size(); j ++)
res + = matrix [i] [j];
return res;
}

作为额外的好处,您不需要传递矩阵的维数到函数: matrix.size()表示第一个维度, matrix [0] .size()表示第二个维度。

I want to make class library, a function which its parameter is a matrix of unknown size, and the user will create his own matrix with his own size and pass it to this function to do some operations on his matrix like this, will be the function

calculateDeterminantOfTheMatrix( int matrix[][])
{
   some Operations to do on matrix 
}

解决方案

Multi-dimensional arrays are not very well supported by the built-in components of C and C++. You can pass an N-dimension array only when you know N-1 dimensions at compile time:

calculateDeterminantOfTheMatrix( int matrix[][123])

However, the standard library supplies std::vector container, that works very well for multi-dimension arrays: in your case, passing vector<vector<int> > &matrix would be the proper way of dealing with the task in C++.

int calculateDeterminantOfTheMatrix(vector<vector<int> > &matrix) {
    int res = 0;
    for (int i = 0 ; i != matrix.size() ; i++)
        for(int j = 0 ; j != matrix[i].size() ; j++)
            res += matrix[i][j];
    return res;
}

As an added bonus, you wouldn't need to pass dimensions of the matrix to the function: matrix.size() represents the first dimension, and matrix[0].size() represents the second dimension.

这篇关于如何将未知大小的二维数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆