Lesson 180 +10 XP

Sets (std::set)

Sets (std::set)

A std::set holds a collection of values with two auto-promises: the values are unique, and they are kept sorted.

Create and insert

#include <set>

std::set<int> s;
s.insert(3);
s.insert(1);
s.insert(3);   // duplicate, ignored
s.insert(5);

The set now holds {1, 3, 5}. Inserting 3 a second time changed nothing - sets refuse to double-count.

Ask about elements

s.count(3);   // 1 if 3 is in the set, 0 if not
s.erase(3);   // remove 3 if present
s.empty();    // true when it has no elements
s.size();     // how many distinct values it holds

Walk the set

for (int value : s) {
    std::cout << value << "\n";
}

Because sets keep order, the loop naturally visits 1 3 5 low to high, in the sorted sequence.

When a set shines

You need a collection where every single thing appears at most once and a fast count() or find() to test membership. The no-duplicates rule is the selling point; the sorting is a bonus.

TL;DR

  • A std::set keeps values unique and sorted automatically.
  • insert adds once, duplicates ignored.
  • count(x) returns 1 or 0; erase(x) removes x.
  • empty() and size() work as usual.
  • Pick it when you need to check membership fast and never allow duplicates.