Search code examples
c++c++11dictionaryinitializationinitializer-list

C++11 Nested Map with List-Initialization


I have a nested map, i.e., map<int, map<int, string>> that I'd like to initialize with an initializer list. I can use an initializer list to initialize a single-level map, but can't seem to figure out the proper syntax for a nested map. Is it even possible?

MWE:

// This example shows how to initialize some maps
// Compile with this command:
//      clang++ -std=c++11 -stdlib=libc++ map_initialization.cpp -o map_initialization

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main(){
    cout << "\nLearning map initialization.\n" << endl;

    map<int, string> level1map = {
        {1, "a"},
        {2, "b"},
        {3, "c"}
    };

    for (auto& key_value : level1map) {
        cout << "key: " << key_value.first << ", value=" << key_value.second << endl;
    }

//  This section doesn't compile
//  map<int, map<int, string>> level2map = {
//      {0,
//          {0, "zero"},
//          {1, "one"},
//          {2, "two"}
//      },

//      {1,
//          {0, "ZERO"},
//          {1, "ONE"},
//          {2, "TWO"}
//      }
//  };

    return 0;
}

Solution

  • You're just missing a pair of braces around the inner map contents:

    map<int, map<int, string>> level2map = {
        {0, {
            {0, "zero"},
            {1, "one"},
            {2, "two"}
        }},
    
        {1, {
            {0, "ZERO"},
            {1, "ONE"},
            {2, "TWO"}
        }}
    };
    

    Perhaps it would be more noticeable if you wrote it out in one line. A list of four things:

    {0, {0, "zero"}, {1, "one"}, {2, "two"}}
    

    vs. a list of 2 things, where the 2nd thing is a list of 3 things:

    {0, {{0, "zero"}, {1, "one"}, {2, "two"}}}