std::unordered_set<Key> · C++
insert / emplace
Inserts an element if absent.
std::pair<iterator, bool> insert(const value_type& value);
Complexity
| Average | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) per element |
Assumes: Good hash.
Hash, scan the bucket, link a node.
Tested example
std::unordered_set<int> seen;
assert(seen.insert(4).second); // inserted
assert(!seen.insert(4).second); // already present: unchanged
assert(seen.size() == 1);
Parameters
- value
- The element.
Behaviour
- Returns
- An iterator to the element and whether it was inserted.
- Errors and preconditions
- std::bad_alloc; exceptions from hashing (map unchanged).
- Changes
- At most one new node; may rehash.
- Memory and invalidation
- Rehash invalidates iterators, not references.