gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:15:20 26 4
gpt4 key购买 nike

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

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

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

最佳答案

我建议围绕 std::array<checker_type, 8 * 8> 创建一个包装类(因为使用一维数组模拟二维数组通常被证明由于缓存而更快)。这样您就可以轻松创建和复制此类板。

#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 - 一个提供动态数组功能和大量实用程序的类模板:

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?

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

关于C++如何动态保存大量数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57137736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com