相当于Python字典的C ++ [英] C++ equivalent of Python dictionaries
问题描述
我目前正在用AI制作井字游戏程序,在翻译这行代码(python)时遇到了一些麻烦:
I'm currently making a tic-tac-toe program with AI and i'm having a bit of a trouble translating this line of code (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
值的哈希表.
The closest match in C++ would be an std::unordered_map<int, int>
. This is a hash table mapping int
keys to int
values.
#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 []
访问元素
You can access elements using operator[]
, for example
std::cout << RANKS[0] << std::endl; // prints "2"
请注意,C ++标准库还具有 std :: map
类模板,该模板可让您创建类似但按排序的查找表 std :: map< int,int>
,并具有对数外观-和插入的复杂性.但是python unordered_map
更接近.
Note that the C++ standard library also has the std::map
class template, which allows you to create a similar but ordered look-up table std::map<int, int>
, with logarithmic look-up and insertion complexity. But python dict
s are hash tables, so unordered_map
is a closer match in terms of behaviour.
这篇关于相当于Python字典的C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!