2

How can I emplace to std::map<std::string, std::map<std::string,std::string>>?

tried with myMap.emplace(std::make_pair("STRING", std::make_pair("STR","STR"))) but got error message cannot convert std::pair<_Ty1,_Ty2> to const std::pair<_Ty1,_Ty2>

leon22
  • 5,280
  • 19
  • 62
  • 100

2 Answers2

1
myMap.emplace(
      std::make_pair(
            "STR1"
         ,   std::map< std::string, std::string>(
                {
                   std::make_pair("STR2", "STR3")
                }
             )
      )
);

Should work.

Nikita Smirnov
  • 813
  • 8
  • 17
  • Did you included ? – Nikita Smirnov Feb 24 '17 at 10:24
  • A little more weird code then: `(std::initializer_list>({ std::make_pair("STR2", "STR3") }))` in nested map's constructor, if first variant doesn't really work. – Nikita Smirnov Feb 24 '17 at 10:27
  • 1
    Initializer lists are not supported by VS2012 :-( – leon22 Feb 24 '17 at 10:27
  • Ah, yeap, I didn't noticed tag( Then I have another bad idea, but it's not a real emplacing - create nested map outside, and just pass as parameter to first std::make_pair. And for only interest - here is C++'17 coming, and VS2012 is still actual?) – Nikita Smirnov Feb 24 '17 at 10:31
  • In that environment I have to use the old compiler, but nevertheless I will use insert instead of emplace! Thx – leon22 Feb 24 '17 at 11:41
0

Using std::piecewise_construct you can emplace() as follows

   myMap.emplace(
      std::piecewise_construct,
      std::forward_as_tuple("STRING"),
      std::forward_as_tuple(
         std::initializer_list<std::pair<std::string const, std::string>>{
            {"STR", "STR"} }));

but I think it's a little clearer emplace an empty map and immediatly after emplace the "STR"s in it, as follows

   myMap.emplace(std::piecewise_construct,
                 std::forward_as_tuple("STRING"),
                 std::forward_as_tuple()).first->second.emplace("STR", "STR");
ManuelSchneid3r
  • 15,850
  • 12
  • 65
  • 103
max66
  • 65,235
  • 10
  • 71
  • 111