Search code examples
c++dictionaryinitialization

c++ initialize a map of maps more nicely


I have just started learning c++ today and am having a hard time finding an elegant way to initialise a map of maps. At the moment, the horrible method is:

typedef std::map < char, map < char, int > >  terribly_initialised_map;

and then

terribly_initialised_map plz_help;
plz_help['m']['e'] = 1;
....
...
..
.

There must be a better way?


Solution

  • In C++11, it's a lot easier:

    map_type someMap{
        {'m', {
            {'e', 1},
            {'f', 2}
        }},
        {'a', {
            {'b', 5}
        }}
    };
    

    This makes use of list initialization, using std::map's list constructor (the one that takes a std::initializer_list<std::pair<Key, Value>>). The pairs can also be list initialized with the two stored values.

    In C++03, you can do decently well with boost::map_list_of, but it might not be much better than what you have for nested maps, especially with the outer call needing to be a specific list_of call to eliminate an ambiguity:

    using boost::assign::list_of;
    using boost::assign::map_list_of;
    map_type someMap = 
        list_of<map_type::value_type>
        ('m', 
            map_list_of
            ('e', 1)
            ('f', 2)
        )
        ('a', 
            map_list_of
            ('b', 5)
        )
    ;