Codectionary / Developer documentation / C++

C++ std::unordered_set membership

C++11 unordered_set stores unique keys with average constant-time lookup. It is useful when membership matters more than sorted traversal.

Syntax

std::unordered_set<T> seen; auto [it, inserted] = seen.insert(value);

Examples

C++ std::unordered_set membership

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <unordered_set>
#include <string>
#include <iostream>
int main() {
    std::unordered_set<std::string> seen;
    for (const auto& name : {"Ada", "Lin", "Ada"}) {
        if (seen.insert(name).second) std::cout << name << '\n';
    }
    std::cout << seen.size() << '\n';
}
  1. Output: Ada, Lin, then 2. Printing occurs during input traversal, so it does not depend on hash-table iteration order. The syntax illustration uses C++17 structured bindings; the program uses C++11.

Best practices

  • Do not rely on traversal order. Rehashing invalidates iterators, and poor hashing can make worst-case lookup linear.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading