了解数组,指针和引用。尝试将棋盘8x8大小的数组作为函数参数传递以打印该数组。
是否不可能使用基于范围的循环,还是应该使用基本的for循环?还是我只是错误地设置了第一个值?没有模板。
第一个值[0][0]
应为1,而不是1。
#include <iostream>
void print(int (&board)[8][8])
{
for (auto &x : board)
{
for (auto &y : board)
{
std::cout << board[*x][*y] << '\t';
}
std::cout << std::endl;
}
}
int main (int argc, const char **argv)
{
// Attempting to initialize all 8x8 to 0
int board[8][8] = { { 0 } };
// Set position [0][0] to value 1;
board[0][0] = { 1 };
// Print chessboard
print(board);
}
输出量
/* Output (Incorrect)
* 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1
*
*/
预期
/* Output (CORRECT)
* 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
*
*/
x
和y
是元素,而不是数组的索引。您可以将基于范围的for循环更改为
for (auto &row : board)
{
for (auto element : row)
{
std::cout << element << '\t';
}
std::cout << std::endl;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句