我目前正在用 AI 制作一个井字游戏程序,但我在翻译这行代码 (python) 时遇到了一些麻烦:
RANKS = dict([(4,3), # center = 3
(0,2),(2,2),(6,2),(8,2), # corners = 2
(1,1),(3,1),(5,1),(7,1)]) # sides = 1
进入 C++
有什么建议吗?
最佳答案
C++ 中最接近的匹配是 std::unordered_map<int, int>
.这是一个哈希表映射 int
int
的键值(value)观。
#include <unordered_map>
std::unordered_map<int, int> RANKS = {
{ 4, 3 },
{ 0, 2 }, { 2, 2 }, { 6, 2 }, { 8, 2 },
{ 1, 1 }, { 3, 1 }, { 5, 1 }, { 7, 1 }
};
您可以使用 operator[]
访问元素, 例如
std::cout << RANKS[0] << std::endl; // prints "2"
请注意,C++ 标准库也有 std::map
类模板,它允许您创建一个类似但有序 的查找表 std::map<int, int>
,具有对数查找和插入复杂性。但是 python dict
s 是哈希表,所以 unordered_map
在行为方面更接近匹配。
关于python - C++ 相当于 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27674009/