std::unordered_set
std::unordered_set<T> is a hash table of unique values. Membership tests and inserts are average O(1). There is no key order. Worst case is O(n) under collisions.
Detailed Explanation
"Have I seen this token?" in a request handler is an unordered_set<string>. You do not need the tokens sorted. You need contains to be cheap. That is the type.
It is unordered_map<T, /*empty*/> in spirit: buckets, std::hash<T>, ==, load factor, reserve. The element is a T, const through the iterator. There is no mapped value.
insert returns {iterator, bool}. find returns an iterator or end(). count is 0 or 1. contains (C++20) is the readable membership test. erase(value) or erase(iterator) removes.
Iteration order is arbitrary and can change on rehash. Do not use an unordered set as a stable sequence. If you need insertion order plus uniqueness, keep a vector and an unordered_set together, or use a library type.
Custom T needs == and a hash. The two must agree: equal values hash equal. A struct hashed on one field and compared on another will lose elements.
unordered_multiset allows duplicates. set keeps order and does not need a hash. For a small, cold set of a dozen ints, a vector plus std::find can be faster than either hash table because it does not allocate nodes.
reserve(n) before filling from a file avoids repeated rehashes. bucket_count and load_factor are the knobs if you are debugging a collision pile-up.
Pointers and references to elements remain valid through rehash; iterators do not. Erase invalidates only iterators to the erased element.
Code Examples
#include <iostream>
#include <string>
#include <unordered_set>
int main() {
std::unordered_set<std::string> seen;
seen.reserve(16);
seen.insert("ada");
std::cout << std::boolalpha << seen.contains("ada") << '\n'; // prints: true
std::cout << seen.insert("ada").second << '\n'; // prints: false
}#include <iostream>
#include <unordered_set>
#include <vector>
int main() {
std::vector<int> ids{1, 2, 2, 3, 1};
std::unordered_set<int> unique(ids.begin(), ids.end());
std::cout << unique.size() << '\n'; // prints: 3
}Common Gotchas
No stable order
printing an `unordered_set` in tests will flake across libraries. Sort a copy if you need a golden string.
Hash/`==` mismatch
the table can fail to find a value you just inserted. Write both, and test them together.
`contains` needs C++20
on C++17 write `find(x) != end()`.
Storing `string_view`
same dangling risk as `set<string_view>`. Own the strings.