Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emplace to std::map of std::map

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>

like image 874
leon22 Avatar asked Apr 16 '26 18:04

leon22


2 Answers

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

Should work.

like image 111
Nikita Smirnov Avatar answered Apr 19 '26 07:04

Nikita Smirnov


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");
like image 33
max66 Avatar answered Apr 19 '26 08:04

max66



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!