C++ std::unordered_set

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

Definition and Usage

In C++, std::unordered_set<T> is a container that stores unique values in a hash table. If you add a value that is already inside, the unordered_set quietly ignores it. Values are not kept sorted. Iteration order is unspecified.

Finding, inserting, and erasing a value are usually average constant time. Check for a value with find() or contains(), add values with insert() or emplace(), and call reserve() before many inserts. Include <unordered_set> to use it.

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

Why choose an unordered_set?

Choose an unordered_set when you only care whether a value is present, want no duplicates, and do not need sorted output, for example unique user ids, visited urls, or a fast membership filter. If you need sorted output or lower_bound-style searches, use std::set. If each key needs an attached value, use std::unordered_map. If you only need a list by position, use a std::vector.

C++ Syntax

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

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

std::unordered_set<int> a;                          // empty
std::unordered_set<int> b = {30, 10, 20, 10};       // unique values, order unspecified
std::unordered_set<std::string> d = {"pear", "apple"};

b.reserve(10);                   // prepare buckets
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::unordered_set vs std::set vs std::vector vs std::unordered_map

Here is a quick comparison of containers that beginners often mix up:

Featurestd::unordered_setstd::setstd::vectorstd::unordered_map
StoresUnique valuesUnique valuesValues (duplicates OK)Key and value pairs
Order of elementsUnspecified (hash buckets)Sorted by valueThe order you added themUnspecified (hash buckets)
Find a value / keyUsually constantLogarithmicLinearUsually constant (by key)
DuplicatesNot allowedNot allowedAllowedUnique keys
Ordered search (lower_bound())NoYesOnly if you sort itNo
Header<unordered_set><set><vector><unordered_map>

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

Several members test or change membership. Pick the one that matches your goal:

WayIf the value is missingUse it when you…
find()Returns end(). The unordered_set is not changed.Need an iterator, or want to erase after a search
contains() / count()Returns false or 0Only need to know whether a value exists
insert()Adds the value (or reports it was already there)Want to add a unique value without duplicates
reserve()Does not look up a valueKnow about how many values you will insert and want fewer rehashes

C++ Examples

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

Example 1 — Add Values and Look Them Up

A first program that adds names three ways, including one repeat. Membership checks avoid relying on iteration order.

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

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

    names.insert("Raj");
    names.insert("Mia");
    names.emplace("Zoe");
    names.insert("Mia");   // ignored duplicate

    std::cout << std::boolalpha;
    std::cout << "has Raj: " << names.contains("Raj") << '\n';
    std::cout << "has Mia: " << names.contains("Mia") << '\n';
    std::cout << "has Tom: " << names.contains("Tom") << '\n';
    std::cout << "size: " << names.size() << '\n';
    return 0;
}

How It Works

  1. std::unordered_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 stored.
  3. contains() checks membership without depending on hash-bucket order. size() is 3, not 4, because the duplicate was never stored.

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

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

C++
#include <iostream>
#include <unordered_set>

int main() {
    std::unordered_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 << "contains 30: " << std::boolalpha << ids.contains(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 unordered_set is not changed.
  3. find(99) returns end() because 99 is not stored. contains(30) is true. The final size is 4.

Example 3 — Drop Duplicates Faster with reserve()

An unordered_set is great for unique ids. Call reserve() first when you know about how many different values you will see.

C++
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>

int main() {
    std::vector<std::string> words = {"pear", "apple", "fig", "pear", "kiwi", "apple", "pear"};
    std::unordered_set<std::string> unique;
    unique.reserve(words.size());

    for (const std::string& w : words) {
        unique.insert(w);
    }

    std::cout << std::boolalpha;
    std::cout << "has pear: " << unique.contains("pear") << '\n';
    std::cout << "has mango: " << unique.contains("mango") << '\n';
    std::cout << "distinct: " << unique.size() << '\n';
    return 0;
}

How It Works

  1. reserve(words.size()) prepares buckets so the insert loop does less rehashing.
  2. Each insert(w) adds a new word once. Repeated words are ignored.
  3. Six words were read but only four are different, so size() is 4. Membership checks avoid printing in hash order.

Next: C++ std::unordered_set Functions Index

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

Start withWhy
insert()Add a new unique value
find()Search for a value without adding it
reserve()Prepare buckets before many inserts
erase()Remove a value by value or by iterator

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

Frequently Asked Questions

std::unordered_set<T> is a hash table from <unordered_set>. It stores unique values, finds a value in average constant time, and does not keep values sorted. Iteration order is unspecified.
unordered_set uses hashing, is usually faster to find a value, and does not sort values. set keeps values sorted and finds in logarithmic time. Choose set when you need sorted output or lower_bound-style range searches.
unordered_set stores only unique values. unordered_map stores key and value pairs. Use a map when each key needs an attached value.
No. The elements are const, because changing a value could break the hash table. 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::unordered_set Functions index. It lists every member function in this series, from insert() and find() to reserve(), rehash(), and hash_function().

Browse every unordered_set function

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

Function 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