c++传递二维数组

C++ Passing 2D Arrays

本文关键字:二维数组 c++      更新时间:2023-10-16

我正在尝试创建一个扫雷游戏,从平面文件加载板(不,它不是随机的)。根据分配指令,我将传递一个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用户解决您的问题,所以我不太相信这些指导很快就会被严格遵守。