Nikos Iliakis
Nikos Iliakis

Reputation: 167

map inside map in C++

I have a difficult time creating nested maps in C++.

First of all I have typedefed my types

typedef std::map<std::variant<int, std::string>, std::variant<int, long long int, std::string>> SimpleDict;
typedef std::map<std::variant<int, std::string>, std::variant<int, std::string,std::vector<SimpleDict>,SimpleDict>> ComplexDict;

Then I define my map:

ComplexDict m = {
        "MAC0", {

                {"TAG0", "111001011000"},
                {"SEQ", "110000100100"},
                {"IOD", "0000"}

        }

};

However I get No matching constructor for initialization of 'ComplexDic. Even if I change the type of m to std::map< std::string, std::map<std::string, std::string> > for simplicity, I get the same error. I think I'm doing something wrong with the syntax. Could you help?

Upvotes: 0

Views: 119

Answers (1)

Yksisarvinen
Yksisarvinen

Reputation: 22394

In both cases, you miss one set of braces to denote "a pair in top level map":

typedef std::map< std::string, std::map<std::string, std::string> > ComplexDict2;
ComplexDict2 m = {
    { //first pair of map
        "MAC0", {
            {"TAG0", "111001011000"},
            {"SEQ", "110000100100"},
            {"IOD", "0000"}
        }
    } //first pair end
};

For the actual case with variants, it seems that compiler is confused what type should this be:

{
    {"TAG0", "111001011000"},
    {"SEQ", "110000100100"},
    {"IOD", "0000"}
}

You can resolve it by naming the type explicitly:

ComplexDict m = {
    {
        "MAC0", SimpleDict {
            {"TAG0", "111001011000"},
            {"SEQ", "110000100100"},
            {"IOD", "0000"}
        }
    }
};

Upvotes: 2

Related Questions