C++ map insert() Function
Example
Add a new element to a map:
map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
people.insert({"Jenny", 22});
for (auto person : people) {
cout << person.first << " is: " << person.second << "\n";
}
Definition and Usage
The insert() function adds one or more elements to a 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 new element is placed in the correct sorted position.
The insert function is defined in the <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
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 maps in our Maps Tutorial.