Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested map bracket initialization fails to compile

Tiny, very simple code example that showcases the problem:

#include <string>
#include <map>

static std::map<std::string, std::map<std::string, int>> defaults = {
    { std::string("Definitely a string"), { std::string("This too"), 0 }},
};

The error? main.cpp:4:58: No matching constructor for initialization of 'std::map<std::string, std::map<std::string, int> >'

like image 664
LulzCop Avatar asked Feb 12 '23 00:02

LulzCop


1 Answers

You need an extra pair of braces:

#include <string>
#include <map>

static std::map<std::string, std::map<std::string, int>> defaults = {
    { std::string("Definitely a string"), {{ std::string("This too"), 0 }}},
//                                        ^                              ^
};

It's basically the same way as initializing the outer map - the inner map needs to be initialized with an initializer list - one pair of braces - that contains initializer lists for the key-value pairs of the map - another pair of braces per element.

As Matt McNabb noted, you don't have to explicitly construct the std::strings.

like image 159
T.C. Avatar answered Feb 16 '23 02:02

T.C.