在(c ++)中使用二维数组作为函数参数?

时间:2016-03-09 15:49:57

标签: c++

如您所知,多维数组必须具有除第一个之外的所有维度的边界,当我们在main之前定义它时。 我有一个2d矩阵,并希望将其用作函数的参数。这个2d矩阵有一行和一列我必须初始化列... 我知道这些方法:(并且不想使用命令行来定义列的值。)

//1-using a number
void sample(int array[][5]);
int main(){.....}

//2-using a static parameter
#define x 5
void sample(int array[][x]);
int main(){.....}

但不是他们对我有用4,你还有其他建议吗?

实际上这是我的主要代码:

#define colu 7
#define colu_ 7

int compute(char mat1[][colu],int r1,char mat2[][colu_], int r2);
int main(){
.
.
.
int m;
m=compute(mat1,r1,mat2,r2);
cout<<m<<endl;
return 0;}

//****************
int compute(char mat1[][colu],int r1,char mat2[][colu_], int r2){
...
}
//****************

我需要在&#34;计算&#34;中传递这些2d矩阵。功能。

4 个答案:

答案 0 :(得分:1)

如果您不想使用参数,可以始终使用矢量矢量:

void sample(vector<vector<int>>& array)

然后您可以通过以下方式获得相应的尺寸:

array.size();
array[0].size(); // if at least there is a row

另请注意,如评论中所述,使用向量向量与矩阵不同,因为行可能具有不同的大小。

另一种选择是使用单个向量并使用一些数学来访问特定的行col:

double matrix::get( size_t x1, size_t y1 )
{
    return m[ x1 * x + y1 ];
}

答案 1 :(得分:1)

如果您能够使用C99,请使用VLA。

void sample(int rows, int cols, int array[rows][cols]);

在C ++中,使用std::vector<std::vector<int>>而不是2D数组。

void sample(std::vector<std::vector<int>> const& array);

答案 2 :(得分:1)

您可以使用模板自动或直接定义列大小:

template <size_t col1, size_t col2>
int compute(char mat1[][col1], int r1, char mat2[][col2], int r2)
{
    std::cout << "c1: mat 1 is " << r1 << "x" << col1 << "\n";
    std::cout << "c1: mat 2 is " << r2 << "x" << col1 << std::endl;

    return r1;
}

如果您的矩阵大小在编译时已知,您可以像这样使用它:

int main() {

    char mat1[1][1] = { { 'a' } };
    char mat2[2][2] = { { 'b', 'c' },{ 'd', 'e'} };
    compute(mat1, 1, mat2, 2);
    compute(mat1, 1, mat2, 1);
    return 0;
}

然而,如果你需要使用char**,这个实现并不是真的有用......

答案 3 :(得分:1)

如果在编译时已知数组维度,则可以使用模板:

template<int X, int Y>
void foo(int (&array)[X][Y]) {
    std::cout << X << ' ' << Y << '\n';
    for(const auto& arr : array) {
        for(const auto& i : arr) {
            std::cout << i << ' ';
        }
        std::cout << '\n';
    }
}

int main() {
    int asdf[2][5] = {
        { 1, 2, 3, 4, 5 },
        { 6, 7, 8, 9, 10 }
    };
    foo(asdf);
}

如果您使用new动态分配数组,则无效。