More on HashCompare
In general, the definition of HashCompare
must provide two signatures:
A hash method that maps a
Key
to asize_t
An
equal
method that determines whether two keys are equal
The signatures fall naturally in a single class because if two keys are equal, they must hash to the same value. Otherwise, the hash table might not work. You could trivially meet this requirement by always hashing to 0, but that would cause tremendous inefficiency. Ideally, each key should hash to a different value, or at least the probability of two distinct keys hashing to the same value should be kept low.
The methods of HashCompare
should be static unless you need to have them behave differently for different instances. If so, construct the concurrent_hash_map
using the constructor that takes a HashCompare
as a parameter. Example 5-6 is a variation on an earlier example that uses instance-dependent methods. The instance performs either case-sensitive or case-insensitive hashing and comparison, depending upon an internal flag, ignore_case
.
Example 5-6. Hash compare
// Structure that defines hashing and comparison operations class VariantHashCompare { // If true, then case of letters is ignored. bool ignore_case; public: size_t hash( const string& x ) { size_t h = 0; for( const char* s = x.c_str(); *s; s++ ) h = (h*17)^*(ignore_case?tolower(*s):*s); return h; } // True if strings are equal bool equal( const string& x, const string& y ) { if( ignore_case ) strcasecmp( x.c_str(), y.c_str() )==0; ...
Get Intel Threading Building Blocks now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.