传递给两个维度大小不同的相同函数矩阵
Passing to a same function matrices with different sizes of both dimensions
我有几个不同大小的常量矩阵,比方说
const int denoise[][3] = {...}
。
const int deconv[][4] = {...}
然后我定义了一个类似void handleMatrix(const int* const*){...}
的函数希望能处理这些矩阵。但这是不正确的。
我尝试过的一种方法是使用如下模板:
template<typename Ty> void handle Matrix(const Ty m){...}
它在 vs2013 上完美运行。
但是我应该如何在不使用模板的情况下将这些矩阵传递给函数?
您的矩阵是 int[3]
的数组。如果你想传递 C 风格的参数,你会传递一个指针,数组的第一个元素加上一个大小:
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)));
您应该使用 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,如果您发表评论,我可以针对任何其他版本进行修改。
我有几个不同大小的常量矩阵,比方说
const int denoise[][3] = {...}
。
const int deconv[][4] = {...}
然后我定义了一个类似void handleMatrix(const int* const*){...}
的函数希望能处理这些矩阵。但这是不正确的。
我尝试过的一种方法是使用如下模板:
template<typename Ty> void handle Matrix(const Ty m){...}
它在 vs2013 上完美运行。
但是我应该如何在不使用模板的情况下将这些矩阵传递给函数?
您的矩阵是 int[3]
的数组。如果你想传递 C 风格的参数,你会传递一个指针,数组的第一个元素加上一个大小:
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)));
您应该使用 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,如果您发表评论,我可以针对任何其他版本进行修改。