CodeBlanks Logo Icon CodeBlanks

std::set

Learn unique ordered collections with std::set.

std::set

std::set stores unique and sorted elements. You add with insert; duplicates are ignored. size() returns the unique count. Its internal structure is a red-black tree.

Example: std::set<int> s; s.insert(1); s.insert(1); s.insert(2);. The second insert(1) is ignored; s.size() returns 2. s.count(1) returns 1 (present). Sorted iteration: for (int x : s) std::cout << x;. This prints in ascending order.

Set ordering

set keeps elements sorted. Iteration is in ascending order. count(key) checks presence; find(key) returns an iterator. lower_bound and upper_bound are used for range queries.

Example: std::set<int> s = {3, 1, 2};. Even though the list order is 3, 1, 2, the set content is 1, 2, 3. s.count(2) returns 1. s.find(2) returns an iterator pointing to 2; if not found, it returns s.end(). This provides fast presence checks.

Practice Work with set

Create std::set<int> s;. Add 1, 1, 2, 3 with insert. Print s.size().

Starter code

main.cpp
#include <iostream>
#include <set>

// create a set and add elements (with duplicates)

int main() {
    // print the unique count
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <set>

int main() {
    std::set<int> s;
    s.insert(1);
    s.insert(1);
    s.insert(2);
    s.insert(3);
    std::cout << s.size() << std::endl;
    return 0;
}

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the insert call

Question
s.insert(____);
Answer
s.insert(1);

Explanation: s.insert(1); adds 1 to the set (unique).

2 Match the property

Term Meaning
unique No duplicates
sorted Ordered
insert Add (duplicates ignored)
size() Unique count

3 If you insert 1, 1, 2 into std::set<int>, what does size() return?

main.cpp
std::set<int> s; s.insert(1); s.insert(1); s.insert(2);
  • 3
  • 1
  • 2 Correct answer
  • 0

Explanation: Duplicates are ignored; unique elements are 1 and 2 → size 2.

All lessons in Intermediate