Search code examples
c++dictionaryinitializationinitialization-list

C++ Multiple Maps Inside Map


In python I can have a dictionary inside a dictionary like so:

dict = {  'a': { 1:1, 2:2, 3:3 }, 
          'b': { 1:1, 2:2, 3:3 }, 
          'c': { 1:1, 2:2, 3:3 }   }

In C++ I have to use a map inside another map:

std::map< std::string, std::map<int, int> > map1

But how do I achieve the same structure as the python example? Haven't been able to find any examples of this.

std::map< std::string, std::map<int, int, int> > ??

std::map<std::string, std::map<int, int>, std::map<int, int>, std::map<int, int> > ??

Solution

  • If you mean an initialization of the map object then it could look like

    #include <iostream>
    #include <string>
    #include <map>
    
    int main() 
    {
        std::map< std::string, std::map<int, int> > m =
        {
            { "a", { { 1, 1 }, { 2, 2 }, { 3, 3 } } },
            { "b", { { 1, 1 }, { 2, 2 }, { 3, 3 } } },
            { "c", { { 1, 1 }, { 2, 2 }, { 3, 3 } } },
        };
    
        for ( const auto &p1 : m )
        {
            std::cout << p1.first << ": ";
            for ( const auto &p2 : p1.second )
            {
                std::cout << "{ " << p2.first << ", " << p2.second << " } ";
            }
            std::cout << '\n';
        }
    
        return 0;
    }
    

    The program output is

    a: { 1, 1 } { 2, 2 } { 3, 3 } 
    b: { 1, 1 } { 2, 2 } { 3, 3 } 
    c: { 1, 1 } { 2, 2 } { 3, 3 }