Created
June 26, 2012 06:38
-
-
Save ashwin/2993828 to your computer and use it in GitHub Desktop.
Using unordered_set with hash function
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
#include <iostream> | |
#include <unordered_set> | |
struct Point | |
{ | |
int x, y; | |
bool operator == ( const Point& p ) const | |
{ | |
return ( ( x == p.x ) && ( y == p.y ) ); | |
} | |
}; | |
struct PointHash | |
{ | |
std::size_t operator () ( const Point& p ) const | |
{ | |
// Modified Bernstein hash | |
// http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx | |
return ( 33 * p.x ) ^ p.y; | |
} | |
}; | |
typedef std::unordered_set< Point, PointHash > PointUSet; | |
int main() | |
{ | |
PointUSet pset; | |
// Insert | |
Point parr[3] = { | |
{ 0, 0 }, | |
{ 10, -20 }, | |
{ 99, 1000 } | |
}; | |
pset.insert( parr[0] ); | |
pset.insert( parr[1] ); | |
pset.insert( parr[2] ); | |
// Find | |
if ( pset.end() == pset.find( parr[1] ) ) | |
std::cout << "Not found\n"; | |
else | |
std::cout << "Found\n"; | |
// Remove | |
pset.erase( parr[2] ); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment