Junior — Middle
In what situations is it preferable to use std::unordered_map?
sobes.tech AI
Answer from AI
std::unordered_map is preferable when high-speed access to elements by key is important, and the order of elements does not matter. It is a hash table providing amortized access time of O(1) on average, unlike std::map, which is implemented as a balanced tree and provides access in O(log n).
Situations for using std::unordered_map:
- When you need to quickly search, insert, or delete elements by key.
- When the order of elements is not important.
- When keys have a good hash function that minimizes collisions.
Example of usage:
#include <unordered_map>
#include <string>
#include <iostream>
int main() {
std::unordered_map<std::string, int> wordCount;
wordCount["apple"] = 3;
wordCount["banana"] = 2;
std::cout << "apple: " << wordCount["apple"] << std::endl;
return 0;
}