C++ equivalent of Python dictionaries

后端 未结 5 802
后悔当初
后悔当初 2021-02-14 06:42

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),                      


        
5条回答
  •  故里飘歌
    2021-02-14 06:49

    The closest match in C++ would be an std::unordered_map. This is a hash table mapping int keys to int values.

    #include 
    
    
    std::unordered_map RANKS = {
            { 4, 3 },
            { 0, 2 }, { 2, 2 }, { 6, 2 }, { 8, 2 },
            { 1, 1 }, { 3, 1 }, { 5, 1 }, { 7, 1 }
    };
    

    You can access elements using operator[], for example

    std::cout << RANKS[0] << std::endl; // prints "2"
    

    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, with logarithmic look-up and insertion complexity. But python dicts are hash tables, so unordered_map is a closer match in terms of behaviour.

提交回复
热议问题