c++传递二维数组
C++ Passing 2D Arrays
我正在尝试创建一个扫雷游戏,从平面文件加载板(不,它不是随机的)。根据分配指令,我将传递一个2d数组给一个加载函数,然后该函数将解析作为命令行参数传递的文件。
无论如何,我的问题是传递二维数组。做这件事的正确方法是什么?下面是我到目前为止的代码:
#include <iostream>
using namespace std;
struct Tile
{
bool mine, visible;
int danger;
};
bool loadBoard( Tile **board, string filename );
const int gridSize = 6;
int main( int argc, char* argv[] )
{
Tile board[ gridSize ][ gridSize ];
loadBoard( board, argv[ 1 ] );
system("PAUSE");
return EXIT_SUCCESS;
}
bool loadBoard( Tile **board, string filename ) {
}
既然你正在使用c++,为什么不使用
std::vector<std::vector<Tile>>
优先于c风格的数组?
既然你似乎需要使用c风格的数组,你可以使用arpanchaudhury建议的方法,或者你可以传递Tile*
并做类似
static void loadBoard(Tile *board, int rows, int cols, string filename) {
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
Tile* tile = &board[(row*gridSize)+col];
// populate Tile
}
}
}
如果您想传递2d-array,请指定数组中的列数。
bool loadBoard( Tile board[][size], string filename ) {}
,但最好使用向量而不是简单的数组,因为您不需要指定预定义的大小
只要你用的是c++…
#include <iostream>
using namespace std;
struct Tile
{
bool mine, visible;
int danger;
};
// load a square board of declared-size.
template<size_t N>
void loadboard( Tile (&board)[N][N], const std::string& filename)
{
// load board here.
cout << "Loading from file: " << filename << endl;
for (size_t i=0;i<N;++i)
{
cout << "board[" << i << "]: [ ";
for (size_t j=0;j<N;++j)
{
// load element board[i][j] here
cout << j << ' ';
}
cout << ']' << endl;
}
cout << endl;
}
int main()
{
Tile board[6][6];
loadboard(board, "yourfilename.bin"); // OK dims are the same
Tile smaller[3][3];
loadboard(smaller, "anotherfile.bin"); // OK. dims are the same
// Tile oddboard[5][6];
// loadboard(oddboard, "anotherfile.bin"); // Error: dims are not the same.
return 0;
}
Loading from file: yourfilename.bin
board[0]: [ 0 1 2 3 4 5 ]
board[1]: [ 0 1 2 3 4 5 ]
board[2]: [ 0 1 2 3 4 5 ]
board[3]: [ 0 1 2 3 4 5 ]
board[4]: [ 0 1 2 3 4 5 ]
board[5]: [ 0 1 2 3 4 5 ]
Loading from file: anotherfile.bin
board[0]: [ 0 1 2 ]
board[1]: [ 0 1 2 ]
board[2]: [ 0 1 2 ]
当然,也可能有不使用该语言的模板特性的"具体说明"。不过,我敢打赌,这些指导也不包括让SO用户解决您的问题,所以我不太相信这些指导很快就会被严格遵守。
相关文章:
- 将值从二维数组输出到文本文件
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在C++中获取二维数组中最少的一列数?
- 如何使用用户输入变量制作二维数组?
- C++ 中动态二维数组的访问冲突
- 遍历二维数组的所有子数组
- 将二维数组的所有元素插入到一维数组中
- 在函数中传递二维数组
- 为什么指针在对二维数组进行排序时无法正常工作?
- 创建 std::string 的二维数组的最佳做法
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 元素在二维数组 c++ 中的出现次数
- 执行 c++ 二维数组
- C++ 中的二维数组初始化为一个值
- 在C++中初始化第一维大小未知的二维数组
- 如何在二维数组中存储值?