Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 31: Set and Unordered Set | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 31 of 45

·C++

Lesson 31: Set and Unordered Set

11 min

Course progress69%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Unique, sorted (`std::set`) and hash‑based (`std::unordered_set`) containers
  • Custom comparators and hash functions
  • Complexity analysis
  • Typical use cases

Set and Unordered Set

std::set stores unique elements in a sorted order using a balanced binary tree (typically a red‑black tree). std::unordered_set uses a hash table for average O(1) lookup, insertion, and deletion.


Typical operations

  • insert, find, erase, count.
  • std::set provides ordered iteration; unordered_set does not guarantee order.
  • Custom comparators (std::set) or hashers/equality predicates (std::unordered_set).

Example: Using std::set for automatic sorting and duplicate elimination

std::set<int> s;
s.insert(5);
s.insert(3);
s.insert(5); // duplicate ignored
for (int v : s) std::cout << v << ' '; // prints 3 5
std::cout << '\
';

Example: std::unordered_set with a custom hash for a user‑defined type

struct Point { int x, y; };
struct PointHash {
    std::size_t operator()(const Point& p) const noexcept {
        return std::hash<int>{}(p.x) ^ (std::hash<int>{}(p.y) << 1);
    }
};
struct PointEq {
    bool operator()(const Point& a, const Point& b) const noexcept {
        return a.x == b.x && a.y == b.y;
    }
};
std::unordered_set<Point, PointHash, PointEq> pts;
pts.insert({1,2});
pts.insert({1,2}); // duplicate ignored by hash/equality
std::cout << \"Set size: \" << pts.size() << '\
';

Tip: Reserve bucket count with pts.reserve(n) when you know the expected number of elements to reduce rehashing.


<Alert type="info">When ordering matters (e.g., for range queries), prefer std::set. For fast membership tests, choose std::unordered_set.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 30: Deque ContainerContinue to lesson 32Lesson 32: Map and Unordered MapBack to C++ Course curriculum