C++函数中推广二维数组
C++ generalize two dimension array in function
我想用C++编写一个函数,它接受任何大小的矩阵并打印出来。
我的代码如下,它可以工作。但我的问题:
1( 这是最佳实践吗? 2(为什么使用(int *)
铸造有效,而static_cast<int *>
则无效?
谢谢
#include <iostream>
using namespace std;
void print_matrix(int *, int, int);
int main()
{
int mat[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int mat2[5][5] = {{1, 2, 3, 40, 50},
{4, 5, 6, 70, 80},
{7, 8, 9, 10, 20},
{17, 18, 19, 10, 20},
{71, 81, 91, 110, 120}
};
print_matrix((int *)mat2, 5, 5);
cout << endl;
print_matrix((int *)(mat), 3, 3);
cout << endl;
// static cast does not work:
// error: invalid static_cast from type 'int [3][3]' to type 'int*'|
// print_matrix(static_cast<int *>(mat), 3, 3);
return 0;
}
void print_matrix(int *matPtr, int row, int col)
{
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++)
cout << *(matPtr + col * i + j) << 't';
cout << endl;
}
}
这是最佳实践吗?
不,不是。
最好使用函数模板。
template <size_t NR, size_t NC>
void print_matrix(int (&matrix)[NR][NC])
{
...
}
并将其称为:
print_matrix(mat2); // NR and NC are deduced by the compiler
为什么使用
(int *)
进行铸造有效,而static_cast<int *>
则无效?
鉴于
int mat[3][3] = { ... };
以下指针具有相同的数值,即使指针的类型不同。
int (*p1)[3][3] = &mat;
int (*p2)[3] = &mat[0];
int *p3 = &mat[0][0];
因为这种巧合,使用(int*)
作品。
使用static_cast<int*>
不起作用,因为当 2D 数组衰减到指针时,它不会衰减到int*
-mat
衰减到int (*)[3]
(指针指向"3int
s 的数组"(,mat2
衰减到int (*)[5]
(指针指向"5int
s 的数组"(。它们不能投射到一般的int*
。
相关文章:
- 在函数中传递二维数组
- C++函数中推广二维数组
- 如何将 50 行和 50 列的二维数组编码为一个为元素随机分配星号的函数?
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 如何在 c++ 中初始化构造函数中的二维数组
- 编写一个可以使二维数组平坦的函数
- 二维数组传入没有全局定义 (M x N) 的函数
- 如何将二维数组作为类中的私有变量,然后在构造函数中设置它
- 如何在函数中将二维数组作为参数传递,并在 C++ 中返回二维数组
- 类的二维数组和C++中的构造函数调用
- 将二维数组传递到只需要一维数组的函数中(C++)
- 接受来自函数的二维数组(int 类型)并将其返回到主函数
- 二维数组的递归函数
- 如何制作返回C 中二维数组的函数
- 通过指针将二维数组传递给 c++ 中的函数
- C++:传递二维数组以执行函数
- 如何在C++中将动态二维数组传递给函数
- 将二维数组从数据文件传递给函数并输出内容
- 将二维数组传递给函数会产生奇怪的错误
- 二维数组 - 函数