Explain the difference between std::map and std::unordered_map. What are the time complexities for their operations, and how do they handle collisions?
Last updated
std::mapis a sorted balanced tree (typically red-black) needingoperator<, with O(log n) insert/find/erase.std::unordered_mapis an unordered hash table with O(1) average but O(n) worst-case operations. Collisions use separate chaining (per-bucket lists), and rehashing invalidates iterators.Choose
std::mapfor ordered traversal or range queries,std::unordered_mapfor fastest average lookups.