std::set

Sets in C++: How std::set Works

Learn how C++ std::set stores unique values in sorted order, with examples of insert, find, erase, custom comparators, and how it differs from hash sets.

On this page
  1. Creating a set and adding values
  2. Checking the result of insert
  3. Looking up values
  4. Removing values and checking size
  5. Why values stay sorted
  6. Storing your own types
  7. Elements cannot be changed in place
  8. How fast is it?
  9. std::set compared with other containers
  10. Common mistakes
  11. Choosing a set

std::set is a container from the <set> header that holds unique values in sorted order. Adding a value that is already present does nothing, and inserts, lookups and removals all take logarithmic time. A set suits jobs like checking whether a value exists or keeping a collection free of duplicates.

Creating a set and adding values

Include <set> and name the element type in angle brackets. Braces can supply the starting values:

#include <iostream>
#include <set>

int main() {
    std::set<int> numbers = {5, 1, 3, 3, 1};

    numbers.insert(4);

    for (int n : numbers) {
        std::cout << n << ' ';
    }
    std::cout << '\n';
}

The program prints 1 3 4 5. The repeated 3 and 1 are stored only once, and the values come out in ascending order.

You can also start with an empty set, as in std::set<int> ids;. A set can be built from any range of values. For example, std::set<int> unique(v.begin(), v.end()); copies the values of a std::vector<int> named v into a set and drops the duplicates on the way.

Checking the result of insert

insert returns a std::pair. Its second member is true when the value was added and false when the set already held it:

std::set<int> ids;

auto first = ids.insert(7);
std::cout << first.second << '\n';  // 1: 7 was added

auto again = ids.insert(7);
std::cout << again.second << '\n';  // 0: 7 was already there

insert never replaces an existing element, so the set stays as it was. emplace also works and builds the value in place, as in ids.emplace(8).

Looking up values

Since C++20, contains answers a yes-or-no question:

if (ids.contains(7)) {
    std::cout << "7 is in the set\n";
}

Before C++20, count does the same job. It returns 1 if the value is present and 0 if not, because a set holds each value at most once.

find returns an iterator to the element, or end() when the value is missing. Compare against end() before you use the result:

auto it = ids.find(42);
if (it != ids.end()) {
    std::cout << *it << " is in the set\n";
} else {
    std::cout << "42 is not in the set\n";
}

Removing values and checking size

erase(value) removes the value if it is there and returns how many were removed, which is 0 or 1. clear() removes every element. size() and empty() report how many values the set holds.

auto removed = ids.erase(7);  // removed is 1

Why values stay sorted

By default, std::set orders its keys with std::less<Key>, which uses operator<. Each insert places the new value in the right spot, so iteration always visits the values in order.

To change the order, pass a comparator as the second template argument. std::greater<int> from <functional> reverses it:

#include <functional>
#include <iostream>
#include <set>

int main() {
    std::set<int, std::greater<int>> scores = {70, 95, 82};
    for (int s : scores) {
        std::cout << s << ' ';
    }
    std::cout << '\n';
}

The program prints 95 82 70.

A comparator also decides what counts as a duplicate. If the comparator says neither value is less than the other, the set treats them as the same element. A lambda that compares string lengths shows this:

#include <set>
#include <string>

int main() {
    auto by_length = [](const std::string& a, const std::string& b) {
        return a.size() < b.size();
    };
    std::set<std::string, decltype(by_length)> words(by_length);

    words.insert("cat");
    words.insert("dog");  // same length as "cat", so it is not added
}

The comparator object is passed to the constructor, which works in any version of C++ from C++11 on. For more on lambda syntax, see c lambda function.

Storing your own types

To store a struct, define operator< as a member, or pass a comparator. This struct orders points by x and then by y:

struct Point {
    int x;
    int y;

    bool operator<(const Point& other) const {
        if (x != other.x) return x < other.x;
        return y < other.y;
    }
};

std::set<Point> points;
points.insert(Point{1, 2});
points.insert(Point{1, 2});  // duplicate, not added
points.insert(Point{0, 5});

For more on writing operators like this, see operator overloading in c.

Elements cannot be changed in place

Elements are const when you reach them through an iterator, so *it = 10; will not compile. To change a value, erase it and insert the new one. Changing a key in place could break the sorted order, which is why the language does not allow it.

How fast is it?

Insert, erase and find each take logarithmic time in the number of elements. Most standard libraries build a set on a red-black tree, a balanced binary search tree that keeps the tree height in check. Each element lives in its own node, so a set usually uses more memory per value than a std::vector.

std::set compared with other containers

  • std::unordered_set uses a hash table. It does not keep values in order, but lookups are typically constant time on average. The hash-based version is covered in hashset in c.
  • std::multiset allows duplicates and keeps them in sorted order.
  • std::map stores key-value pairs in sorted order. For a closer look at it, see dictionary in c.
  • std::vector is the usual choice when you need positions or repeated values.

Common mistakes

  • Expecting duplicates. A set quietly drops them. If you need to know whether a value was added, check the second member that insert returns.
  • Indexing with brackets. A set has no operator[], so numbers[0] does not compile. Iterate instead, or use begin().
  • Forgetting operator<. A custom type needs operator< or a comparator. Without one, the compiler reports an error from deep inside the library headers.
  • Assuming insertion order. A set orders values by comparison, not by when you added them.

Choosing a set

Use std::set when you need unique values, fast membership checks and sorted output. If order does not matter, std::unordered_set is often the better fit. If you need repeated values, use std::multiset, or a std::vector when you also need positions.

Keep exploring

Guides from other topics

All topics →

How to Use cout in C++

Learn how to use cout in C++ to print text, numbers and variables, add new lines, and format output, with short complete examples you can compile and run.

cout 4 min read

Header Guards in C++

A header guard stops a header from being included twice in one source file. Learn how #ifndef and #pragma once work, with examples and common mistakes.

Header Guards 4 min read