C++ map emplace() Function
Example
Add a new element to a map:
map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
people.emplace("Liam", 24);
for (auto person : people) {
cout << person.first << " is: " << person.second << "\n";
}
Definition and Usage
The emplace() function adds a new element to a map. You give it the key and the value, and it builds the element directly inside the map.
If the key already exists, nothing is added. The new element is placed in the correct sorted position.
The emplace function is defined in the <map> header file.
Tip: emplace() works like insert(), but you do not need curly braces {} around the key and the value.
Syntax
map.emplace(keyType key, valueType value)
keyType is the type of the keys, and valueType is the type of the values in the map, like string and int in the example.
Parameter Values
| Parameter | Description |
|---|---|
| key | Required. The key of the new element. |
| value | Required. The value of the new element. |
Technical Details
| Returns: | A pair. Its first is an iterator to the element, and its second is true if the element was added, or false if it already existed. |
|---|
Related Pages
Read more about maps in our Maps Tutorial.