Last active
June 13, 2018 03:33
-
-
Save huklee/a6aaaefcc06b726677528dceab389a57 to your computer and use it in GitHub Desktop.
[C++ STL] unordered_map (hash table) example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <unordered_map> | |
// how to make a new datatype in hashtable | |
struct X{int i,j,k;}; | |
namespace std { | |
template <> | |
class hash<X>{ | |
public : | |
size_t operator()(const X &x ) const{ | |
return hash<int>()(x.i) ^ hash<int>()(x.j) ^ hash<int>()(x.k); | |
} | |
}; | |
} | |
void std_unorderedmap_test(){ | |
// 01. initialization & list all elements in it | |
std::unordered_map<std::string, std::string> mymap; | |
mymap = {{"USA","D.C"}, {"KO", "Seoul"}, {"Japan", "Tokyo"}}; | |
std::cout << "mymap contains:"; | |
for (auto it = mymap.begin(); it != mymap.end(); it++){ | |
std::cout << " " << it->first << ":" << it->second; | |
// it->first = key, it->second = value | |
} | |
std::cout << std::endl; | |
// 02. how to use it in general way | |
std::unordered_map<int, int> ht; | |
ht[1] = 10; | |
ht[2] = 20; | |
std::cout << ht[1] << std::endl; | |
std::cout << ht.find(2)->second << std::endl; | |
if (ht.find(3) == ht.end()) | |
std::cout << "3 doesn't have the key in ht" << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment