C++ Reference ยท Containers
std::map insert, emplace, find and operator[]
Reference for adding and reading std::map elements: insert, emplace, try_emplace, insert_or_assign, operator[], at, find and contains, and how they differ.
A std::map (and std::unordered_map) offers several ways to add an element and several ways to read one, and they differ in a way that matters: whether they overwrite an existing value, whether they construct a default value, and whether they construct the new element at all when the key is already present.
The short version: operator[] is convenient but inserts a default value for a missing key; at() throws; find() and contains() never modify the map; insert and emplace never overwrite; insert_or_assign always does; try_emplace avoids constructing the value when the key exists.
std::map<std::string, int> m; m.insert({"a", 1}); // does nothing if "a" exists m["a"] = 2; // inserts or overwrites auto it = m.find("zzz"); // m.end() when missing
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
std::pair<iterator, bool> insert(const value_type& v); // also insert(P&&), insert(first, last), insert({..}) std::pair<iterator, bool> emplace(Args&&... args); std::pair<iterator, bool> try_emplace(const Key& k, Args&&... args); // C++17 std::pair<iterator, bool> insert_or_assign(const Key& k, M&& value); // C++17 T& operator[](const Key& k); T& at(const Key& k); iterator find(const Key& k); bool contains(const Key& k) const; // C++20
| Name | Description |
|---|---|
v |
A std::pair<const Key, T> (or something convertible to one). |
args |
Arguments forwarded to construct the element (emplace) or just the mapped value (try_emplace). |
k |
The key. |
value |
The new mapped value for insert_or_assign. |
Returns: the pair versions return an iterator to the element with that key and a bool that is true if a new element was inserted. operator[] and at return a reference to the mapped value; find returns an iterator or end().
Errors / undefined behavior: at throws std::out_of_range if the key is missing. operator[] requires T to be default constructible. Dereferencing the end() iterator is undefined.
Usage notes
insert/emplacekeep the old value. Check the returnedboolif you need to know.emplaceis allowed to build the node before it checks for the key, then throw it away (some implementations skip this for simple key types, as the example above shows).try_emplaceis guaranteed to look first, so it never constructs the value or moves from its arguments when the key exists.insert_or_assignis the explicit "set this key" operation and, unlikem[k] = v, works for types without a default constructor.operator[]on a missing key inserts a value-initialized element (0 forint). It is exactly what you want for counters and exactly what you do not want for a lookup.- Do not use
operator[]on aconstmap; it does not compile. Useatorfind. - Lookup then insert is two searches. Use the returned iterator from
insert/try_emplace, orlower_boundplus a hinted insert, if you need speed. - Hints:
insert(hint, v)andemplace_hint(hint, ...)make sorted bulk insertion O(1) amortized per element when the hint is right. - All of these work the same way on
std::unordered_map;containsis C++20 for both.
Related
- std::map, std::unordered_map, Node handles
- Lessons: std::map, std::unordered_map