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:
| Parameter | Type | Description |
|---|---|---|
| std::map | Ordered Map | O(log n) Red-Black tree ordered by key. |
| std::unordered_map | Hash Table | O(1) average constant-time hash lookups. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C++ std::vector (Dynamic Arrays): Methods and Memory
Master std::vector for dynamic contiguous arrays with push_back, emplace_back, and indexing.
C++ std::set and std::pair / std::tuple Explained
Store unique ordered items with std::set and group heterogeneous values with std::pair and std::tuple.
C++ std::string and std::string_view (C++17)
Master text manipulation with std::string and high-performance zero-copy std::string_view.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.