Efficiently insert elements into a map
The map
class is an associative container that holds key-value pairs, where keys must be unique within the container.
There are a number of ways to populate a map container. Consider a map
defined like this:
map<string, string> m;
You can add an element with the []
operator:
m["Miles"] = "Trumpet"
You can use the insert()
member function:
m.insert(pair<string,string>("Hendrix", "Guitar"));
Or, you can use the emplace()
member function:
m.emplace("Krupa", "Drums");
I tend to gravitate toward the emplace()
function. Introduced with C++11, emplace()
uses perfect forwarding to emplace (create in place) the new element for the container. The parameters are forwarded directly to the element constructors. This is quick, efficient, and easy to code.
Though it's certainly an improvement over the other options, the problem with emplace()
is that it...