std::set
std::set<T> is an ordered collection of unique values. Insert, erase, and lookup are O(log n). Iteration walks the values from smallest to largest according to the comparator.
Detailed Explanation
A set answers "have I seen this?" and "give me everything in order". Unique visitor ids you want to print sorted, a collection of time points you will merge, the keys of a sparse index: those are sets. If you also need a value next to each key, use map. If you do not need order, use unordered_set.
The node stores a T. The T is const from the iterator's point of view: *it is const T&. Changing *it would break the tree. To "update" an element in C++17, extract the node, modify the value, and insert the node again.
insert(x) returns {iterator, bool}. The bool is false if x was already present. emplace constructs in place. find, count (0 or 1), contains (C++20), lower_bound, and upper_bound match map without the mapped type.
The comparator defaults to std::less<T>. T must be ordered. If two values are equivalent (!(a<b) && !(b<a)), the set keeps one. Equivalence is not always ==; a comparator that only looks at an id field treats two structs with the same id as the same element even if other fields differ.
std::multiset keeps duplicates. A set does not.
Iterators stay valid on insert and on erase of other elements, like map. Each element is a heap node. A vector<T> that you sort and unique can be smaller and faster if you build once and query many times with binary_search.
A set of pointers compares pointer values, not the objects. A set of string_view is legal and dangerous: the views can dangle. Prefer owning string keys unless the owners are guaranteed to outlive the set.
Code Examples
#include <iostream>
#include <set>
#include <string>
int main() {
std::set<std::string> tags;
tags.insert("cpp");
auto [it, ok] = tags.insert("cpp");
std::cout << std::boolalpha << ok << '\n'; // prints: false
tags.insert("stl");
for (const auto& t : tags) std::cout << t << ' ';
std::cout << '\n'; // prints: cpp stl
}#include <iostream>
#include <set>
int main() {
std::set<int> ids{10, 20, 30, 40};
auto it = ids.lower_bound(25);
std::cout << *it << '\n'; // prints: 30
}Common Gotchas
Comparator equivalence is not `==`
a set with a comparator on `user.id` will refuse a second user with the same id even if `==` would say they differ.
`count` is 0 or 1
do not use it as a histogram. Use `map<T, int>` or `unordered_map`.
`set<string_view>` does not own text
inserting `firstWord(localString)` and then destroying the string leaves a dangling view in the set.