C++ unordered_map insert() Function
Example
Add a new element to an unordered map:
unordered_map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
people.insert({"Jenny", 22});
cout << "Jenny is: " << people["Jenny"];
Definition and Usage
The insert() function adds one or more elements to an unordered map. Each element is a key and a value inside curly braces {}.
If the key already exists, the element is not added, and the old value is kept.
The insert function is defined in the <unordered_map> header file.
Note: insert() does not change the value of a key that already exists. Use at() or square brackets [] to change a value.
Syntax
unordered_map.insert(pair)
Parameter Values
| Parameter | Description |
|---|---|
| pair | Required. The element to add: a key and a value inside curly braces, like {"Jenny", 22}. To add several elements at once, put them in a list, like {{"Jenny", 22}, {"Liam", 24}}. |
Technical Details
| Returns: | When you add one element: 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. When you add several elements: nothing. |
|---|
Related Pages
Read more about unordered maps in our Unordered Map Tutorial.