将两个维度大小不同的矩阵传递给同一个函数
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上运行良好。
但是我应该如何将这些矩阵传递给不使用模板的函数?
你应该使用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)));
相关文章:
- 为什么std::async使用同一个线程运行函数
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 如何将不同的函数签名映射到同一个 std::map?
- 如果两个线程调用同一个函数,但函数中的所有变量都是局部变量,我还需要担心线程之间共享数据吗?
- 两个单链列表共享同一个节点和析构函数两次删除相同的内存
- 有可能在同一个字符序列上有一个类似函数的宏和一个类似对象的宏吗
- 当调用来自同一个重载的非常量版本成员函数时,可以删除常量限定符吗
- 如何在同一个主文件中转发声明类似模板函数的模板类
- 如何在同一个类中同时具有参数化构造函数和默认构造函数
- 具有模板化成员函数的类,是同一个类
- C++ 结构函数体调用另一个结构函数,同一个模块
- 类成员函数调用类友元函数(都是同一个类)可能
- 为什么要将类的线程函数设置为静态,以便在同一个类中可以访问
- C++内联函数的定义必须在同一个文件中
- C++未定义的引用,尽管函数是在同一个文件中定义的
- 指向同一个模板化函数的不同实例的指针保证比较不相等
- 在调用函数时,使用对象的同一个实例作为参数和调用对象
- 在编译时用不同的函数创建同一个类的对象
- 在同一个fstream对象上使用getline的两个函数
- 如果基类和派生类都需要使用同一个函数,回调函数应该去哪里?