C ++如何动态保存大量数组?

C++ How to hold lots of arrays dynamically?

好的,基本上我正在使用 C++ SDL2 库构建一个简单的西洋跳棋游戏

目前我将游戏棋盘状态数据保存在一个 8x8 二维数组中,这是棋盘上所有可能的棋盘 space。 数组内的值是:0 表示空 space,1 表示红色格子,2 表示蓝色格子。

我基本上已经使用这个棋盘作为逻辑完成了整个游戏,现在我将实施 minimax 算法以添加计算机 AI 作为对手。所以我需要做的是获取所有可能的棋盘状态并在算法中使用它。现在我正试图找到以动态方式存储一堆数组(棋盘状态)的正确方法,因为我不会每次都确切知道会有多少状态。有什么简单的方法可以使用主数组来保存所有板状态(2d 数组)?必须是动态的,数组只能是静态的吧?

我建议在 std::array<checker_type, 8 * 8> 周围创建一个包装器 class(因为使用一维数组模拟二维数组通常会因缓存而更快)。这样你就可以很容易地创建和复制这样的板。

#include <array>
#include <iostream>
#include <vector>

namespace game {
    enum class checker_type {
        empty, red, blue
    };

    struct board {
        std::array<checker_type, 8 * 8> data{};

        struct proxy_row {
            std::array<checker_type, 8 * 8>& data_ref;
            const std::size_t row;

            proxy_row(std::array<checker_type, 64>& data_ref, const size_t row) noexcept
                    : data_ref(data_ref), row(row) { }

            checker_type& operator [] (const std::size_t col) const noexcept {
                return data_ref[8 * row + col];
            }
        };

        struct const_proxy_row {
            const std::array<checker_type, 8 * 8>& data_ref;
            const std::size_t row;

            const_proxy_row(const std::array<checker_type, 64>& data_ref, const size_t row) noexcept
            : data_ref(data_ref), row(row) { }

            const checker_type& operator [] (const std::size_t col) const noexcept {
                return data_ref[8 * row + col];
            }
        };

        proxy_row operator [] (const std::size_t row) noexcept {
            return proxy_row(data, row);
        };

        const_proxy_row operator [] (const std::size_t row) const noexcept {
            return const_proxy_row(data, row);
        }
    };
}

void print_board(const game::board& board) noexcept {
    for (int i = 0; i < 8; ++i) {
        for (int j = 0; j < 8; ++j) {
            std::cout << static_cast<int>(board[i][j]) << ' ';
        }
        std::cout << '\n';
    }
}

至于为 运行 minmax 算法创建多个板,您可以使用 std::vector - 一个 class 模板,它提供了具有许多实用程序的动态数组功能:

int main() {
    game::board board{};

    board[0][0] = game::checker_type::blue;
    board[1][1] = game::checker_type::blue;
    board[2][2] = game::checker_type::red;

    print_board(board);

    std::vector<game::board> boards{};

    const auto size = 1000;
    boards.reserve(size); // reserve memory for *size* boards
    for (int i = 0; i < size; ++i) {
        boards.emplace_back(); // creating *size* boards to run minmax algorithm
    }
}

详细说明您的思考过程:

Right now I am trying to find the right way to approach storing a bunch of arrays (board states) in a dynamic way since I will not know exactly every time how many states there will be.

如果您事先不知道数据需要多少内存,那么您想要一种动态方式来存储某些数据是正确的。 std::vector 是处理该问题的绝佳工具。

[Array] needs to be dynamic, and arrays can only be static right?

错了。首先,staticnotdynamic相反的。您可以拥有动态、静态数组(例如 static int* arr = new int[10];)。