...

/

Efficiently Insert Elements into a Map

Efficiently Insert Elements into a Map

Learn to insert elements into a map efficiently.

We'll cover the following...

The map class is an associative containerAn associative container is a type of data structure that enables efficient retrieval of values based on a unique key or identifier, without requiring traversal through other elements. 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;

We can add an element with the [] operator:

m["Miles"] = "Trumpet"

We can use the insert() member function:

m.insert(pair<string,string>("Hendrix", "Guitar"));

Or, we can use the emplace() member function:

m.emplace("Krupa", "Drums");

Many programmers 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 ...