Last active
June 22, 2020 18:54
-
-
Save naveenspace7/d44e137e788b6fc7a686125091b4ff9a to your computer and use it in GitHub Desktop.
This is a small demo showing how to properly use std::unordered_set in C++
This file contains 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
/* | |
* std::unordered_set unlike a std::set is implementation of chaining hash table. | |
* Therefore, it requires additional implementation to get it to work. | |
* This demo tries to show the requirements for such an implementation. | |
*/ | |
#include <iostream> | |
#include <algorithm> | |
#include <unordered_set> | |
#include <functional> | |
using namespace std; | |
class Person | |
{ | |
public: | |
int age, height; | |
Person(int a, int h): age(a), height(h) { | |
} | |
bool operator<(const Person& a_person) const { | |
return this->age < a_person.age; | |
} | |
bool operator==(const Person& a_person) const { | |
return this->age == a_person.age && this->height == a_person.height; | |
} | |
}; | |
namespace std | |
{ | |
template <> | |
struct hash<Person> | |
{ | |
size_t operator()(const Person& p) const { | |
size_t ret_val = hash<int>()(p.age) + hash<int>()(p.height); | |
cout << "hash = " << ret_val << endl; | |
return ret_val; | |
} | |
}; | |
} | |
int main() | |
{ | |
unordered_set<Person> p_set; | |
p_set.insert(Person(10,4)); | |
p_set.insert(Person(9,3)); | |
p_set.insert(Person(14,5)); | |
for_each(begin(p_set), end(p_set), [](const Person& p) { cout << p.age << " and " << p.height << endl;}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment