The choice between std::unordered_map
and std::map
depends on your specific requirements and the characteristics of your data. Here are some guidelines to help you decide when to use each:
Use std::unordered_map
 when:
std::unordered_map
 provides average constant-time complexity (O(1)) for these operations.std::unordered_map
 does not maintain any particular order of elements.Use std::map
 when:
std::map
 is an ordered associative container that keeps elements sorted by keys.std::map
 provides these guarantees.Here's an example illustrating a scenario where std::map
is preferred:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> ageMap{
{"Alice", 25}, {"Bob", 30},
{"Charlie", 35}, {"David", 40}};
auto lower = ageMap.lower_bound("B");
auto upper = ageMap.upper_bound("D");
for (auto it = lower; it != upper; ++it) {
std::cout << it->first << ": "
<< it->second << '\n';
}
}
Bob: 30
Charlie: 35
In this example, std::map
is chosen because we want to retrieve people within a specific range of names (keys). The lower_bound()
and upper_bound()
functions efficiently find the range of elements based on the sorted order of keys.
On the other hand, if fast lookup is the primary concern and the order of elements is not important, std::unordered_map
would be a better choice.
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<
std::string, std::string> phoneBook{
{"Alice", "1234567890"},
{"Bob", "9876543210"},
{"Charlie", "5555555555"}
};
// Lookup phone number by name
std::string name = "Bob";
auto it = phoneBook.find(name);
if (it != phoneBook.end()) {
std::cout << "Phone number of " << name
<< ": " << it->second << '\n';
}
}
Phone number of Bob: 9876543210
In this case, std::unordered_map
provides fast lookup of phone numbers based on names, which is the primary operation required.
Consider the specific requirements of your application, such as the need for ordering, range-based operations, and the expected performance of different operations, when deciding between std::unordered_map
and std::map
.
Answers to questions are automatically generated and may not have been reviewed.
std::unordered_map
Creating hash maps using the standard library's std::unordered_map
container