std::unordered_map<Key, T> · C++
operator[] / at
operator[] returns the value, inserting a value-initialised one if the key is missing; at() throws instead.
T& operator[](const Key& key); T& at(const Key& key);
Complexity
| Average | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) |
One lookup, plus an insert for operator[] on a missing key.
Tested example
std::unordered_map<std::string, int> counts;
counts["a"] += 1; // missing key: inserts a value-initialised int (0) first
counts["a"] += 1;
assert(counts["a"] == 2);
(void)counts["typo"]; // reading through [] also inserts!
assert(counts.size() == 2);
bool threw = false;
try {
(void)counts.at("nobody"); // at() never inserts; it throws
} catch (const std::out_of_range&) {
threw = true;
}
assert(threw);
Parameters
- key
- The key.
Behaviour
- Returns
- A reference to the mapped value.
- Errors and preconditions
- at(): std::out_of_range for a missing key.
- Changes
- operator[] may insert.
- Memory and invalidation
- operator[] may rehash (invalidating iterators).