Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent of Python dictionaries

Tags:

c++

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

into C++

any suggestions?

like image 752
Jenny Calisay Avatar asked Dec 28 '14 05:12

Jenny Calisay


People also ask

Does C have a dictionary?

Generally, the C standard library does not include a built-in dictionary data structure, but the POSIX standard specifies hash table management routines that can be utilized to implement dictionary functionality.

Does C++ have dictionary like Python?

Like Python, C++ comes with a great set of containers. The most commonly used are vectors and dictionaries.

What can I use instead of a dictionary in Python?

defaultdict. defaultdict handles our previous error by building on top of dictionaries. It does not give a KeyError like the regular dictionaries. However, whenever you try to access or “assign to” a key that is not there, it will create that key and give it a default value that was already specified .

Can == operator be used on dictionaries?

According to the python doc, you can indeed use the == operator on dictionaries.


2 Answers

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 }
};

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<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.

like image 107
juanchopanza Avatar answered Oct 10 '22 18:10

juanchopanza


You could use a map or unordered_map for this (and they'd work fine) but given that your keys are a dense set of integers (I.e. all the integers from 0 to N) there are better choices.

I'd probably use an std::array instead. It would look something like this:

std::array <char, 9> vals = { 2, 1, 2, 1, 3, 1, 2, 1, 2 };

This gives pretty much the same syntax and observable behavior, but will typically save quite a bit of memory and probably CPU time as well.

like image 41
Jerry Coffin Avatar answered Oct 10 '22 16:10

Jerry Coffin