Map
A map is a generalized array that consists of key-value pairs. A dictionary is considered to be a Abstract Data Type.
How to implement
Built-in Implementation
C++
Don’t use the square brackets (yet), use the other built-in functions that you can check here: https://en.cppreference.com/w/cpp/container/map
insert something → map::emplace
get something → map::at
map
vs. unordered_map
map | unordered_map | |
---|---|---|
Ordering | increasing order (by default) | no ordering |
Implementation | Self-Balancing Binary Search Tree | Hash Table |
search time | Average, Worst Case | |
Insertion time | + Rebalance | Same as search |
Deletion time | + Rebalance | Same as search |
If the value of a key is requested but the map does not contain it, the key is automatically added to the map with a default value.
The function count checks if a key exists in a map:
The following code prints all the keys and values in a map:
Delete from a map
Some other small insights
Recently discovered that you don’t need to do this when counting.
I keep forgetting this for time to time
unordered_map<pair<int,int> int>
does not exist. The hash function for apair<int,int>
is not defined.
Implementation in Python
Unordered Map
In Python, the map is just a dictionary. This is an unordered map
Ordered Map
Use SortedDict
Competitive Programming
The hash function can be reverse engineered to produce lots of hash collisions. https://codeforces.com/blog/entry/62393
- Therefore, preferable to use a regular
map