C++ unordered_map emplace() Function
Example
Add a new element to an unordered map:
unordered_map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
people.emplace("Liam", 24);
cout << "Liam is: " << people["Liam"];
Definition and Usage
The emplace() function adds a new element to an unordered map. You give it the key and the value, and it builds the element directly inside the unordered map.
If the key already exists, nothing is added.
The emplace function is defined in the <unordered_map> header file.
Tip: emplace() works like insert(), but you do not need curly braces {} around the key and the value.
Syntax
unordered_map.emplace(keyType key, valueType value)
keyType is the type of the keys, and valueType is the type of the values in the unordered 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 unordered maps in our Unordered Map Tutorial.