无法在C++中遍历2D数组
fail to iterate through 2D array in C++
我正在为我的测试学习C++,我以前在那里学习java,现在有很多困惑。我正在尝试打印布尔值的2D数组,如果为true,则返回#,并且?如果为false。我已经尝试过首先初始化数组,我认为这是有效的,如果我不使用迭代器(printGrid),我可以在特定的数组位置打印值。下面是我的代码
#include<iostream>
void printGrid(bool a[][10]){ // why this method doesn't work?
for(int i = 0; i < sizeof(a)/ (sizeof(*a)) ; i++){
for(int j = 0; j < sizeof(a)/ (sizeof(*a)) ; j++) {
char x = a[i][j] ? '#' : '?'; // i've using the conditional in my std::cout before, still doesn't work
std::cout << x;
}
std::cout<< std::endl;
}
}
void main(){
bool grid[10][10];
for(int i = 0; i < sizeof(grid)/sizeof(*grid) ; i++){
for(int j = 0; j < sizeof(grid)/sizeof(*grid); j++){
grid[i][j] = 1;
}
}
printGrid(grid); // this doesn't work
std::cout<<( (grid[0][1]) ? "#" : "?" ) << std::endl; // this works fine
getchar();
} // main
我的printGrid哪里出错了?我尝试过使用INT的2D数组,使用相同的设置,使用main之外的函数等,效果很好。知道吗?
编辑:非常感谢你的回答。我的问题还没有得到回答,我的功能出了什么问题?因为我尝试过使用一种设置相同、参数不同的方法,效果很好
void printint(int a[][10]){ // why does this work, and the above doesn't?
for(int i = 0; i < 10 ; i++){
for(int j = 0; j < 10 ; j++) {
std::cout <<( (a[i][j] == 10) ? "a" : "b");
}
std::cout << std::endl;
}
}
当我使用printint打印我的2D数组时,它工作得很好吗?
bool a[][10]
实际上是bool (*a)[10]
,所以sizeof (a)
是指针的大小。
通过引用传递数组:
void printGrid(const bool (&a)[10][10])
实例
使用std::array<std::array<bool, 10u>, 10u>
具有更直观的界面。
这里,您将数组传递给一个函数,该函数被转换为指针,因此您将得到的只是指针的大小。
记住,当传递格式请求数组衰减时,数组衰减为指针,即如果相应的参数被声明为指针(在这种情况下)。如果参数被声明为对数组的引用,则衰减不会发生
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 遍历unordered_map向量
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- C++声明双链表,使用两个 for 循环双向遍历列表并打印
- 如何正确地推回然后遍历堆中对象的向量?
- 遍历二维数组的所有子数组
- 如何在可变参数模板函数中遍历可变参数元组?
- 避免在遍历 IShellItemArray 时出现代码重复
- 从特定键开始遍历地图
- 如何遍历 2D 阵列?
- 如何修复我的代码并使其遍历 2D 数组中的所有行?(C++)
- 无法在C++中遍历2D数组
- 如何以锯齿形顺序遍历 2D 数组