Skip to content

Instantly share code, notes, and snippets.

@huklee
Last active June 13, 2018 03:33
Show Gist options
  • Save huklee/a6aaaefcc06b726677528dceab389a57 to your computer and use it in GitHub Desktop.
Save huklee/a6aaaefcc06b726677528dceab389a57 to your computer and use it in GitHub Desktop.
[C++ STL] unordered_map (hash table) example
#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