⚙️ C++ Intermediate

What is std::map vs std::unordered_map?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

Both are key-value associative containers but with different internal structures and performance: std::map (ordered): implemented as a self-balancing binary search tree (typically Red-Black tree). Elements always sorted by key. std::map<std::string, int> wordCount; wordCount["apple"] = 5; wordCount["banana"] = 3; wordCount.insert({"cherry", 7}); wordCount.emplace("date", 2); // Access: std::cout << wordCount["apple"]; // 5 -- inserts 0 if not found! auto it = wordCount.find("banana"); // Returns iterator or end() if (it != wordCount.end()) std::cout << it->second; // Iteration (always sorted): for (auto& [key, val] : wordCount) { // Structured bindings std::cout << key << ": " << val << "\n"; }. Complexity: O(log n) for insert/find/erase. Use when: need sorted order, need ordered range queries (lower_bound, upper_bound). std::unordered_map (hash map): implemented as a hash table with chaining. No ordering guarantee. std::unordered_map<std::string, int> wordCount; // Same interface, but: // O(1) average, O(n) worst case for all operations wordCount.reserve(1000); // Pre-allocate buckets wordCount.max_load_factor(0.7); // Control rehashing. Complexity: O(1) average for insert/find/erase. Use when: O(1) lookups needed, don't care about order, keys are hashable. Custom hash: struct PairHash { size_t operator()(const std::pair<int,int>& p) const { return std::hash<int>{}(p.first) ^ std::hash<int>{}(p.second) << 32; } }; std::unordered_map<std::pair<int,int>, int, PairHash> m;. Summary: map for ordered operations and range queries; unordered_map for fast lookups. unordered_map is typically 3-10x faster for typical workloads.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.