将两个维度大小不同的矩阵传递给同一个函数

Passing to a same function matrices with different sizes of both dimensions

本文关键字:函数 同一个 两个      更新时间:2023-10-16

我有几个两个维度的不同大小的常数矩阵,比如

const int denoise[][3] = {...}

const int deconv[][4] = {...}

然后我定义一个函数,如void handleMatrix(const int* const*){...}希望处理这些矩阵。但这是不正确的。

我尝试使用一个模板,如:

template<typename Ty> void handle Matrix(const Ty m){...}

它在vs2013上运行良好。

但是我应该如何将这些矩阵传递给不使用模板的函数?

你应该使用typedef,这样你就不必使用任何糟糕的语法:

using matrix_t = int[3][3];

你应该尽可能通过引用传递你的参数:

void handle_matrix(const matrix_t &mat){
    // do something with 'mat'
}

如果您想使用原始语法而不使用typedef:

void handle_matrix(const int (&mat)[3][3]){
    // ...
}

,如果您想使用原始语法并通过指针传递:

void handle_matrix(const int (*mat)[3]){
    // ...
}

但是你失去了类型安全,所以我建议不要这样做,只使用最好的选择:typedef并通过引用传递。


编辑

你在@Kerrek SB回答的评论中说你的矩阵大小会不同。

下面是如何处理这个问题的方法,并且仍然保持良好的方法:

template<size_t Columns, size_t Rows>
using matrix_t = int[Columns][Rows];
template<size_t Columns, size_t Rows>
void handle_matrix(const matrix_t<Columns, Rows> &mat){
    // ...
}

考虑到我假设你可以在我的回答中使用c++ 14,如果你留下评论,我可以为任何其他版本修改它。

您的矩阵是int[3] s的数组。如果你想要c风格的参数传递,你应该传递一个指针,数组的第一个元素加上size:

using Row = int[3];
void foo(const Row * p, std::size_t n_cols)
{
    for (std::size_t i = 0; i != n_cols; ++i)
    {
        for (int n : p[i]) { std::cout << n << ' '; }
        std::cout << 'n';
    }
}

使用例子:

Row * matrix = new Row[40]();
foo(matrix, 40);
delete [] matrix;

带有类型变量:

Row matrix[] = { {1,2,3}, {2,3,4} };
foo(matrix, std::distance(std::begin(matrix), std::end(matrix)));
相关文章: