Basic Usages
unordered_map<int, int> hashmap;// 2. insert a new (key, value) pairhashmap.insert(make_pair(2, 3));// 3. insert a new (key, value) pair or update the value of existed keyhashmap[1] = 1;hashmap[1] = 2;// 4. get the value of a specific keyhashmap[1]// 5. delete a keyhashmap.erase(2);// 6. check if a key is in the hash mapif (hashmap.count(2) <= 0);// 7. get the size of the hash maphashmap.size()// 8. iterate the hash mapfor (auto it = hashmap.begin(); it != hashmap.end(); ++it) {cout << it->first << "," << it->second << endl;}// 9. clear the hash maphashmap.clear();// 10. check if the hash map is emptyif (hashmap.empty())
Iterating over list of keys:
for (Type key : keys) {
if (hashmap.count(key) > 0) {
if (hashmap[key] satisfies the requirement) {
return needed_information;
}
}
// Value can be any information you needed (e.g. index)
hashmap[key] = value;
}
(to be continued…)
Iterating over map
for (auto& it : myMap) {
vec.push_back(it);
}
Sorting map based on value
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
// Comparator function to sort pairs by second value
bool sortByVal(const std::pair<int, int>& a, const std::pair<int, int>& b) {
return (a.second < b.second);
}
int main() {
// Define a map
std::map<int, int> myMap = {{1, 40}, {2, 30}, {3, 60}, {4, 20}};
// Copy elements to a vector of pairs
std::vector<std::pair<int, int>> vec;
for (auto& it : myMap) {
vec.push_back(it);
}
// Sort the vector by value
std::sort(vec.begin(), vec.end(), sortByVal);
// Print the sorted vector
for (auto& it : vec) {
std::cout << it.first << ": " << it.second << std::endl;
}
return 0;
}
Tips
- When counting frequency, don’t need to check if the hashmap[x] exists.
// don't do this:
if (hashmap.count(x) > 0) hashmap[x]++;
else hashmap[x] = 1;
// do this:
hashmap[x]++;
// same for adding up the frequency:
for (...){
sum += hashmap[x];
}