unordered_map
The unordered_map
is an associative container in C++ that stores data in key-value pairs, similar to a dictionary or hash table. Unlike the standard map
container, unordered_map
uses a hash table implementation that provides average constant-time complexity O(1)
for search, insertion, and deletion operations. However, the elements are not stored in any particular sorted order, making it ideal for scenarios where fast access is more important than maintaining order.
The unordered_map
is particularly useful in applications requiring frequent lookups, such as caching systems, database indexing, counting frequencies of elements, and implementing symbol tables in compilers. It excels in scenarios where you need to associate unique keys with values and perform rapid searches based on those keys.
Syntax
std::unordered_map<key_type, value_type> map_name;
Parameters:
key_type
: The data type of the keys stored in theunordered_map
value_type
: The data type of the values associated with the keysmap_name
: The identifier name for theunordered_map
instance
Return value:
The unordered_map
container itself does not return a value, but its member functions return various types depending on the operation (iterators, boolean values, references, etc.).
Example 1: Creating and Initializing
This example demonstrates the basic creation and initialization of an unordered_map
:
#include <iostream>#include <unordered_map>#include <string>int main() {// Create an empty unordered_mapstd::unordered_map<int, std::string> colors;// Initialize using initializer liststd::unordered_map<int, std::string> fruits = {{1, "Apple"},{2, "Banana"},{3, "Orange"}};// Display the initialized mapstd::cout << "Fruits map contains:" << std::endl;for (const auto& pair : fruits) {std::cout << pair.first << ": " << pair.second << std::endl;}return 0;}
The output of the above code is:
Fruits map contains:3: Orange2: Banana1: Apple
The above code shows how to create an empty unordered_map
and initialize another with key-value pairs using an initializer list. The output displays the fruit IDs and names, demonstrating basic map creation and iteration.
Example 2: Counting Character Frequencies
This example demonstrates using unordered_map
to count the frequency of characters in a string, a common real-world application:
#include <iostream>#include <unordered_map>#include <string>#include <algorithm> // for std::max_elementint main() {std::string text = "programming";std::unordered_map<char, int> charFreq;// Count frequency of each characterfor (char c : text) {charFreq[c]++; // Automatically creates entry if key doesn't exist}// Display character frequenciesstd::cout << "Character frequencies in '" << text << "':" << std::endl;for (const auto& pair : charFreq) {std::cout << "'" << pair.first << "': " << pair.second << " times" << std::endl;}// Find most frequent characterauto maxElement = std::max_element(charFreq.begin(), charFreq.end(),[](const std::pair<char, int>& a, const std::pair<char, int>& b) {return a.second < b.second;});std::cout << "Most frequent character: '" << maxElement->first<< "' appears " << maxElement->second << " times" << std::endl;return 0;}
The output of this code is:
Character frequencies in 'programming':'i': 1 times'm': 2 times'n': 1 times'a': 1 times'g': 2 times'o': 1 times'r': 2 times'p': 1 timesMost frequent character: 'm' appears 2 times
Note: The order of elements in an
unordered_map
is unspecified and may vary across executions.
The above code demonstrates a practical use case where unordered_map
efficiently counts character occurrences. The algorithm has O(n)
time complexity, making it very efficient for frequency analysis tasks commonly used in text processing and data analysis.
Codebyte Example: Building an Employee Database
This example shows how to use unordered_map
to create a simple employee database system for quick employee information retrieval:
This example demonstrates a real-world application where unordered_map
serves as an efficient database for employee records. The constant-time lookup makes it ideal for systems that need to frequently access employee information by ID, such as payroll systems or HR applications.
Frequently Asked Questions
1. What is the difference between map
and unordered_map
?
A map
maintains elements in sorted order using a balanced binary search tree (typically red-black tree), providing O(log n)
operations, while unordered_map
uses a hash table with O(1)
average-case operations but no ordering guarantees.
2. When should I use unordered_map
over map
?
Use unordered_map
when you need faster lookup times and don’t require the elements to be in sorted order. It’s ideal for scenarios like caching, frequency counting, and database indexing where performance is critical.
3. Can I use custom objects as keys in unordered_map
?
Yes, but you need to provide a custom hash function and equality operator for your custom type. The hash function should be provided as a template parameter or through specialization of std::hash
.
unordered_map
- .bucket()
- Returns the bucket number where an element is located in a C++ unordered map.
- .count()
- Returns the number of elements with the specified key.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours