0Pricing
C++ Academy · Lesson

std::unordered_map

Fast hash-based lookup.

What Is unordered_map?

std::unordered_map stores key-value pairs in a hash table. Average lookup, insert, and erase are constant time, but elements have no sorted order.

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<std::string, int> ages;
    ages["Alice"] = 30;
    ages["Bob"] = 25;
    std::cout << ages["Alice"] << '\n';
    return 0;
}

map vs unordered_map

Choose based on needs:

  • map: sorted, O(log n) operations.
  • unordered_map: unordered, O(1) average operations.

Use unordered_map when you only need fast lookups.

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<int, std::string> m{{3, "c"}, {1, "a"}, {2, "b"}};
    std::cout << m.size() << " entries (order not guaranteed)\n";
    return 0;
}

All lessons in this course

  1. std::unordered_map
  2. unordered_set
  3. Custom Hash Functions
  4. Performance Considerations
← Back to C++ Academy