相当于Python字典的C ++ [英] C++ equivalent of Python dictionaries

查看:82
本文介绍了相当于Python字典的C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用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 dict 是哈希表,因此就行为而言, 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 dicts are hash tables, so unordered_map is a closer match in terms of behaviour.

这篇关于相当于Python字典的C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆