Table of Contents

<unordered_set>

<unordered_set> is a hash table of unique elements with O(1) average insertion, deletion, and lookup. Elements are unordered but quickly accessible.

Use unordered_set for fast membership testing; use std::set if you need sorted order.

Example

This example detects duplicate values in a sequence by checking and inserting into an unordered_set, tracking first-seen items.

// compile: g++ -std=c++11 -o unorderedsetexample unorderedsetexample.cpp
// run: ./unorderedsetexample
// description: hash set membership testing
 
#include <unordered_set>
#include <iostream>
 
int main() {
    std::unordered_set<int> seen;
 
    for (int x : {1, 2, 3, 2, 1}) {
        if (!seen.count(x)) {
            std::cout << "first time seeing " << x << "\n";
            seen.insert(x);
        } else {
            std::cout << "already saw " << x << "\n";
        }
    }
 
    return 0;
}