In our Minesweeper implementation, we used a one-dimensional std::vector
to store the cells, but a 2D array is also a viable option. Both approaches have their advantages, and the choice often depends on specific requirements and preferences. Let's explore both methods:
std::vector
We chose to use a std::vector
for its flexibility and ease of use. Here's why:
std::vector
can easily resize at runtime, which is useful if we want to change the grid size dynamically.std::vector
stores elements in contiguous memory, which can lead to better cache performance.std::vector
comes with many useful functions like push_back()
, emplace_back()
, and range-based for loop support.Here's how we implemented it:
#include <vector>
#include "Minesweeper/Cell.h"
class MinesweeperGrid {
public:
MinesweeperGrid(int x, int y) {
using namespace Config;
Children.reserve(GRID_COLUMNS * GRID_ROWS);
for (int Col{1}; Col <= GRID_COLUMNS;
++Col) {
for (int Row{1}; Row <= GRID_ROWS;
++Row) {
constexpr int Spacing{CELL_SIZE +
PADDING};
Children.emplace_back(
x + (Spacing) * (Col - 1),
y + (Spacing) * (Row - 1), CELL_SIZE,
CELL_SIZE, Row, Col);
}
}
}
std::vector<MinesweeperCell> Children;
};
A 2D array could be implemented using std::array
or a raw C-style array. Here's how it might look:
#include <array>
#include "Minesweeper/Cell.h"
class MinesweeperGrid {
public:
MinesweeperGrid(int x, int y) {
using namespace Config;
for (int Col{0}; Col < GRID_COLUMNS;
++Col) {
for (int Row{0}; Row < GRID_ROWS; ++Row) {
constexpr int Spacing{CELL_SIZE +
PADDING};
Children[Row][Col] = MinesweeperCell(
x + (Spacing)*Col, y + (Spacing)*Row,
CELL_SIZE, CELL_SIZE, Row + 1,
Col + 1);
}
}
}
std::array<std::array<MinesweeperCell,
Config::GRID_COLUMNS>,
Config::GRID_ROWS>
Children;
};
This approach has the advantage of more intuitive 2D indexing (Children[row][col]
) and potentially better performance for fixed-size grids.
Both approaches are valid, and the choice often comes down to specific needs and personal preference. In our case, the vector approach provides more flexibility for potential future enhancements, such as dynamic grid sizing.
Answers to questions are automatically generated and may not have been reviewed.
Building a two-dimensional grid of interactive minesweeper cells