Junior — Middle
Can you explain what a std::unordered_map container in C++ is and how it works?
sobes.tech AI
Answer from AI
std::unordered_map is a container from the C++ standard library that implements an associative array (hash table). It stores key-value pairs and provides fast access to elements by key on average in constant time (O(1)).
Main features:
- Uses a hash function to compute the index of the bucket where the element is stored.
- The order of elements is not guaranteed and can be arbitrary.
- Allows efficient insertion, search, and deletion operations by key.
Example usage:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> ages;
ages["Alice"] = 30;
ages["Bob"] = 25;
std::cout << "Alice is " << ages["Alice"] << " years old." << std::endl;
return 0;
}
Thus, std::unordered_map is convenient when access speed by key is important and the order of elements does not matter.