3

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>

1
  • myMap["STRING] = {{"STR", "STR"}}; :-) Commented Feb 24, 2017 at 10:50

2 Answers 2

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

Should work.

Sign up to request clarification or add additional context in comments.

5 Comments

Did you included <initializer_list> ?
A little more weird code then: (std::initializer_list<std::pair<std::string, std::string>>({ std::make_pair("STR2", "STR3") })) in nested map's constructor, if first variant doesn't really work.
Initializer lists are not supported by VS2012 :-(
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?)
In that environment I have to use the old compiler, but nevertheless I will use insert instead of emplace! Thx
1

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"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.