In general, the definition of HashCompare
must provide two signatures:
A hash method that maps a Key
to a size_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; else return x==y; } VariantHashCompare( bool ignore_case_ ) : ignore_case() {} }; typedefconcurrent_hash_map<string,int, VariantHashCompare> VariantStringTable; VariantStringTable CaseSensitiveTable(VariantHashCompare(false)); VariantStringTable CaseInsensitiveTable(VariantHashCompare(true));
The directory examples/concurrent_hash_map/count_strings contains a complete example that uses concurrent_hash_map
to enable multiple processors to cooperatively build a histogram.
18.224.59.231