C++:C++ std::map and std::unordered_map (Hash Tables)
C++•Maps & HashTables

C++ std::map and std::unordered_map (Hash Tables)

std::map keeps keys ordered with O(log n) lookups; std::unordered_map provides O(1) average hash table lookups.

Syntax

#include <unordered_map> std::unordered_map<std::string, int> ages; ages["Alice"] = 30;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
std::mapOrdered MapO(log n) Red-Black tree ordered by key.
std::unordered_mapHash TableO(1) average constant-time hash lookups.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C++ locally:

#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, double> exchangeRates = {
        {"EUR", 1.08},
        {"GBP", 1.27},
        {"JPY", 0.0065}
    };

    // Inserting new entry
    exchangeRates["CAD"] = 0.74;

    // Safe lookup with .find() to avoid default insertion
    std::string currency = "GBP";
    auto it = exchangeRates.find(currency);
    if (it != exchangeRates.end()) {
        std::cout << currency << " rate: " << it->second << " USD\n";
    }

    std::cout << "\nAll Rates in Map:\n";
    for (const auto& [curr, rate] : exchangeRates) {
        std::cout << "  " << curr << " = " << rate << "\n";
    }

    return 0;
}
Expected Output:
GBP rate: 1.27 USD

All Rates in Map:
  CAD = 0.74
  JPY = 0.0065
  GBP = 1.27
  EUR = 1.08

How It Works: Step-by-Step

  • Lines 6-10: Initializes unordered_map with currency string keys and double values.
  • Lines 17-20: Uses .find() to verify key existence without inserting default values.
  • Lines 23-25: Iterates with C++17 structured binding [curr, rate].

Key Concepts

  • map[key] automatically inserts a default-constructed value if the key does not exist.
  • Use find() or contains() (C++20) for read-only lookups.
  • C++17 structured binding auto [k, v] cleanly unpacks pair entries.

Common Mistake: Accidentally inserting keys by reading map[missingKey]

Reading map["missing"] creates an entry with default value 0. Use .find() instead.

❌ Incorrect
if (myMap["non_existent"] > 0) { /* Now "non_existent" is inserted into map! */ }
✅ Correct
if (myMap.find("non_existent") != myMap.end()) { /* Safe check */ }

Related C++ Tutorials & Compiler

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler