Skip to content

Instantly share code, notes, and snippets.

@naveenspace7
Last active June 22, 2020 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naveenspace7/d44e137e788b6fc7a686125091b4ff9a to your computer and use it in GitHub Desktop.
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++
/*
* 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