How to Create unordered_map in C++: Syntax and Example
To create an
unordered_map in C++, include the <unordered_map> header and declare it with key and value types like std::unordered_map<KeyType, ValueType> map;. You can then add, access, and manage key-value pairs efficiently with this hash-based container.Syntax
The basic syntax to create an unordered_map is:
std::unordered_map<KeyType, ValueType> mapName;- declares an empty unordered_map.KeyTypeis the type of the keys (e.g.,int,std::string).ValueTypeis the type of the values stored.- You can also initialize with a list of pairs or specify a custom hash function.
cpp
#include <unordered_map> std::unordered_map<KeyType, ValueType> mapName;
Example
This example shows how to create an unordered_map that maps strings to integers, insert key-value pairs, and print them.
cpp
#include <iostream> #include <unordered_map> int main() { std::unordered_map<std::string, int> ageMap; // Insert key-value pairs ageMap["Alice"] = 30; ageMap["Bob"] = 25; ageMap["Charlie"] = 35; // Access and print values for (const auto& pair : ageMap) { std::cout << pair.first << " is " << pair.second << " years old.\n"; } return 0; }
Output
Alice is 30 years old.
Bob is 25 years old.
Charlie is 35 years old.
Common Pitfalls
Common mistakes when using unordered_map include:
- Forgetting to include the
<unordered_map>header. - Using unsupported key types without providing a hash function.
- Assuming
unordered_mapkeeps elements in insertion order (it does not). - Accessing keys that do not exist creates default values, which may be unintended.
cpp
#include <unordered_map> #include <string> // Wrong: Using a custom class as key without hash function // struct Point { int x, y; }; // std::unordered_map<Point, int> map; // Error: no hash function // Right: Provide a hash function or use supported key types #include <functional> struct Point { int x, y; bool operator==(const Point& other) const { return x == other.x && y == other.y; } }; namespace std { template<> struct hash<Point> { size_t operator()(const Point& p) const { return hash<int>()(p.x) ^ (hash<int>()(p.y) << 1); } }; } int main() { std::unordered_map<Point, int> map; map[{1, 2}] = 5; return 0; }
Quick Reference
Tips for using unordered_map:
- Include
<unordered_map>header. - Use
std::unordered_map<Key, Value>to declare. - Insert or update with
map[key] = value;. - Check existence with
map.find(key) != map.end(). - Iterate with range-based for loops.
Key Takeaways
Include and use std::unordered_map to create an unordered_map.
unordered_map stores key-value pairs with fast average lookup using hashing.
Keys must be hashable; for custom types, provide a hash function and equality operator.
Accessing a non-existing key with operator[] inserts a default value.
Use find() to check if a key exists without inserting.