C++ std::set

Beginner
8 min read
Updated: Nov 2026
3 examples
std::set

Definition and Usage

In C++, std::set<T> is a container that stores unique values in sorted order. If you add a value that is already inside, the set quietly ignores it. Think of it as a guest list where every name appears once and the names are always in alphabetical order.

Inside, a set is a balanced tree, so finding, inserting, and erasing a value all take logarithmic time. Check for a value with find() or contains(), and add values with insert() or emplace(). Include <set> to use it.

This page teaches what a std::set is. The Set Functions index lists every function guide in this series.

Why choose a set?

Choose a set when you only care whether a value is present, want no duplicates, and want the values sorted, for example unique user names, visited ids, or a sorted list of distinct scores. A set has no operator[] and no at(), because the value is its own key. If you also need a value attached to each key, use a std::map.

C++ Syntax

Common ways to create and use a std::set:

C++
#include <iostream>
#include <set>
#include <string>

std::set<int> a;                          // empty set
std::set<int> b = {30, 10, 20, 10};       // sorted: 10 20 30
std::set<int, std::greater<int>> c = {30, 10, 20};   // 30 20 10, biggest first
std::set<std::string> d = {"pear", "apple"};

b.insert(25);                    // add only if the value is new
b.emplace(5);                    // build the value in place
bool has = b.contains(20);       // true (C++20)
auto it = b.find(30);            // iterator, or b.end()
b.erase(10);                     // remove by value
std::size_t n = b.size();        // number of values

std::set vs std::unordered_set vs std::vector

Here is a quick comparison of containers that beginners often mix up. A std::map and a std::multiset are included too:

Featurestd::setstd::unordered_setstd::multisetstd::mapstd::vector
StoresValuesValuesValuesKey and value pairsValues
OrderSortedNo orderSortedSorted by keyThe order you added them
DuplicatesNot allowedNot allowedAllowedKeys not allowed twiceAllowed
Find a valueLogarithmicUsually constantLogarithmicLogarithmicLinear
Ordered search (lower_bound())YesNoYesYesOnly if sorted
Change an element in placeNo, it is constNo, it is constNo, it is constValue yes, key noYes
Header<set><unordered_set><set><map><vector>

When to Use insert(), find() or contains()

A set has no s[i] and no at(). You work with it through these functions. Pick the one that fits:

FunctionWhat happensUse it when you…
insert()Adds the value if it is new. A repeat is ignored, and second of the result is false.Want to add a value and learn whether it was new
find()Returns an iterator, or end() if the value is missing. The set is not changed.Need the iterator, for example to erase the value
contains()Returns true or false (C++20)Only need a yes or no answer
count()Returns 0 or 1Need a yes or no answer before C++20
lower_bound()Returns the first value that is not smaller, or end()Want the first value at or after a limit

C++ Examples

Three short programs that show how std::set works.

Example 1 — Add Values and Loop in Sorted Order

A first program that adds names three different ways, including one repeat. The output is sorted and the repeat is gone.

C++
#include <iostream>
#include <set>
#include <string>

int main() {
    std::set<std::string> names;

    names.insert("Raj");
    names.insert("Mia");
    names.emplace("Zoe");
    names.insert("Mia");

    for (const std::string& n : names) {
        std::cout << n << '\n';
    }
    std::cout << "size: " << names.size() << '\n';
    return 0;
}

How It Works

  1. std::set<std::string> starts empty. It stores only names, with no second value.
  2. insert("Raj"), insert("Mia"), and emplace("Zoe") each add one name. The second insert("Mia") is ignored because Mia is already in the set.
  3. The loop prints Mia, Raj, Zoe, which is alphabetical order and not the order of writing. size() is 3, not 4, because the duplicate was never stored.

Example 2 — Check insert(), find() and count()

These three functions tell you the most about a set. See what insert() reports for a repeat, and what find() does for a missing value.

C++
#include <iostream>
#include <set>

int main() {
    std::set<int> ids = {10, 20, 30};

    auto r1 = ids.insert(40);
    auto r2 = ids.insert(20);
    std::cout << "insert 40: " << (r1.second ? "added" : "already there") << '\n';
    std::cout << "insert 20: " << (r2.second ? "added" : "already there") << '\n';

    auto it = ids.find(99);
    std::cout << "find 99: " << (it == ids.end() ? "not found" : "found") << '\n';
    std::cout << "count 30: " << ids.count(30) << '\n';
    std::cout << "size: " << ids.size() << '\n';
    return 0;
}

How It Works

  1. insert() returns a pair. The second part is true when the value was new. 40 is new, so it is added.
  2. insert(20) finds 20 already there, so second is false and the set is not changed.
  3. find(99) returns end() because 99 is not stored. count(30) is 1, never more, since a set keeps one copy. The final size is 4: 10, 20, 30, 40.

Example 3 — Remove Duplicates, then Search with lower_bound()

A set is a quick way to drop repeated values from a vector. Because the values are sorted, you can also ask for the first value at or after a limit.

C++
#include <iostream>
#include <set>
#include <vector>

int main() {
    std::vector<int> scores = {70, 85, 70, 92, 85, 60, 92};
    std::set<int> unique(scores.begin(), scores.end());

    std::cout << "unique scores:";
    for (int s : unique) {
        std::cout << ' ' << s;
    }
    std::cout << '\n';

    auto it = unique.lower_bound(80);
    if (it != unique.end()) {
        std::cout << "first score from 80: " << *it << '\n';
    }
    std::cout << scores.size() << " scores, " << unique.size() << " different\n";
    return 0;
}

How It Works

  1. The set is built from the whole vector. Every repeat of 70, 85, and 92 is skipped, and the four different values are sorted.
  2. The loop prints 60 70 85 92. The original vector is not changed, so it still has seven values.
  3. lower_bound(80) returns the first value that is not smaller than 80. 60 and 70 are smaller, so it lands on 85. The check against end() keeps the read safe.

Next: C++ std::set Functions Index

After you know what a std::set is, open the function index for a full tutorial on each member function.

Start withWhy
insert()Add a new value to the set
find()Search for a value without adding it
erase()Remove a value, or an iterator position
contains()A clear yes or no check (C++20)

Full list: C++ std::set Functions index (/cpp/set/function).

Frequently Asked Questions

std::set<T> is a container from <set>. It stores unique values, keeps them in sorted order, and finds, inserts, or erases a value in logarithmic time.
A set keeps values in sorted order and uses a balanced tree, so find is logarithmic. An unordered_set uses hashing, has no order, and is usually faster to find a value. Choose set when you need sorted output or range searches such as lower_bound().
A set allows each value once and ignores a repeat. A multiset is also sorted but allows duplicates, so count() can be larger than 1.
No. The elements are const, because changing a value could break the sorted order. To change one, erase the old value and insert the new one, or use extract() in C++17 to move the value out and edit it.
Open the C++ std::set Functions index. It lists every member function, from insert() and find() to lower_bound() and extract(), each with its own tutorial.

Browse every set function

Open the functions index for categorized guides with examples and FAQs.

Set Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful