#include #include #include #include #include #include "hashmap.h" #include "hash.h" bool HashMap::empty() const { return true; } size_t HashMap::size() const { size_t ret = 0; for( unsigned int b = 0; b < NUM_BUCKETS; ++b ) { ret += buckets_[b].size(); } return ret; } namespace { class FirstCompare { public: FirstCompare( const std::string& key ) : key_( key ) { } bool operator()( const HashMap::keyvalue_type& kv ) { return ( kv.first == key_ ); } private: const std::string& key_; }; unsigned int bucket_for_key( const std::string& key ) { return Hash::hash( key ) % NUM_BUCKETS; } HashMap::bucket_type::const_iterator find_in_bucket( const HashMap::bucket_type& bucket, const std::string& key ) { return std::find_if( bucket.begin(), bucket.end(), FirstCompare( key ) ); } } const int* HashMap::find( const std::string& key ) const { unsigned int bucket_num = bucket_for_key( key ); const bucket_type& bucket = buckets_[bucket_num]; bucket_type::const_iterator it = find_in_bucket( bucket, key ); if( it == bucket.end() ) { return NULL; } else { return &( it->second ); } } void HashMap::insert( const std::string& key, int value ) { unsigned int bucket_num = bucket_for_key( key ); bucket_type& bucket = buckets_[bucket_num]; if( find_in_bucket( bucket, key ) == bucket.end() ) { bucket.push_back( std::make_pair( key, value ) ); } }