std::set and std::multiset

Ordered unique/duplicate elements

Interview Relevant: Tree-based containers

Set and Multiset

Red-black tree based. O(log n) operations.

Code Examples

Ordered sets with unique and duplicate elements.

cpp
1#include <set>
2
3// set - unique elements, sorted
4set<int> s = {3, 1, 4, 1, 5};  // {1, 3, 4, 5}
5s.insert(2);   // {1, 2, 3, 4, 5}
6s.erase(3);    // {1, 2, 4, 5}
7
8// Find
9auto it = s.find(4);
10if (it != s.end()) cout << *it;
11bool exists = s.count(4);  // 0 or 1
12
13// Lower/upper bound
14auto lb = s.lower_bound(3);  // First >= 3
15auto ub = s.upper_bound(3);  // First > 3
16
17// multiset - allows duplicates
18multiset<int> ms = {1, 2, 2, 3, 3, 3};
19ms.count(3);        // 3
20ms.erase(ms.find(3)); // Remove ONE 3
21ms.erase(3);        // Remove ALL 3s
22
23// Custom comparator
24set<int, greater<int>> descSet;  // Descending order
25
26struct Person {
27    string name;
28    int age;
29};
30auto cmp = [](const Person& a, const Person& b) {
31    return a.age < b.age;
32};
33set<Person, decltype(cmp)> people(cmp);

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In