我目前正在编写一个带有人工智能的井字游戏程序,但是我在翻译这行代码(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++?
有什么建议吗?
我目前正在编写一个带有人工智能的井字游戏程序,但是我在翻译这行代码(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
值。
#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
是哈希表,因此在行为方面,unordered_map
更为相似。std::map
是一棵自平衡的二叉搜索树,而std::unordered_map
则是一个哈希表。它们的查找分别为O(log N)和O(1),但如果你关心性能,应该使用两者来测试代码。 - juanchopanzadict
是插入有序的(参见此Stackoverflow答案)。因此,自2017年以来,std::map
可能是最好的答案。 - scūriolusstd::map
不同,因为它按键排序而不是插入。稍后我会添加澄清。 - juanchopanzastd::array <char, 9> vals = { 2, 1, 2, 1, 3, 1, 2, 1, 2 };
std::unordered_map
。#include <unordered_map>
std::unordered_map<int, int> dict
{
{
{ 4, 3 },
{ 0, 2 }, { 2, 2 }, { 6, 2 }, { 8, 2 },
{ 1, 1 }, { 3, 1 }, { 5, 1 }, { 7, 1 }
}
};
unordered_map
,不是吗? - juanchopanzaunordered_map
而不是 map
。 - jamylakdict
相对应的是std::map
。要使用类似的语法初始化一个map,请执行以下操作:std::map<int,int> myMap = {{4,3}, # center = 3
{0,2},{2,2},{6,2},{8,2}, # corners = 2
{1,1},{3,1},{5,1},{7,1}}; # sides = 1
map_list_of
。他们页面上的示例是:using namespace boost::assign; // bring 'map_list_of()' into scope
std::map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);
虽然“语言等效”可能类似于std::unordered_map
,但您的用例可能更适合使用直接数组:
int RANKS[] = {2, 1, 2, 1, 3, 1, 2, 1, 2};