STL Data Structures: set and map in Competitive Programming
In competitive programming, std::set and std::map are standard C++ associative containers that efficiently support operations like insertion, deletion, and search in time. They are usually implemented as balanced binary search trees, so all elements (keys) are kept in sorted order. This makes them very useful when you need to maintain a dynamically changing ordered set of values or key–value pairs.
std::set
A set is a container that stores unique keys in sorted order. Basic properties:
- No duplicates: inserting the same value again has no effect.
- Sorted: iteration goes in increasing order of the keys.
- Typical operations:
insert,erase,find,lower_bound,upper_bound.
Typical declaration:
std::map
A map is an ordered dictionary: it stores key–value pairs (key, value), with unique keys and keys sorted by strict weak ordering.
Basic properties:
- Each key appears at most once.
- Access value by key using
operator[]orat. - Insertion, deletion, and search take .
Example of a map from strings to integers: