C++ STL Hash Containers and Performance 
by Thomas Johnson

Listing One

struct terribleHasher {
  size_t operator()(const myClass& myObj) const {
    return 1;
  }
};


Listing Two

template< typename T_TypeToHash >
struct SizeTCastHasher {
  size_t operator()( const T_TypeToHash& i_TypeToHash ) const {
      return size_t( i_TypeToHash );
  }
};


Listing Three

class adFactory {
  ...
  myAdvertisement* createAd(TAdType adType) {
    myAdvertisement* newAd=new myAdvertisement(adType);
    myWebsite* website=websiteFactory.getBestWebsite(newAd);
    website.placeAd(newAd);
    return newAd;

  }
  ...
};
class website {
  public:
  ...
    void placeAd(const myAdvertisement* const ad) {
      myAds.insert(ad);   
    }
    bool doWeShowAd(myAdvertisement* ad) const {
      return myAds.find(ad)!=myAds.end();
    }
  ...
  private:
    __gnu_cxx::hash_set< const myAdvertisement*, 
        SizeTCastHasher< const myAdvertisement* > > myAds;
}


Listing Four

struct ShiftedPairHasher {
  size_t operator()(std::pair<unsigned int, unsigned int> key) {
    return (key.first << ( sizeof(unsigned int) * 8/2)) ^ key.second;
  }
}


Listing Five

#include <iostream>
#include <ext/hash_map>
#include <map>
int doMapBenchmark() {
  typedef __gnu_cxx::hash_map<int,int> TMap;
  //typedef std::map<int,int> TMap;
  std::vector<TMap> myMaps;
  int mySum=0;
  for(int mapCnt=0; mapCnt<1000000; ++mapCnt) {
    TMap myMap;
    for(int i=0; i<10; ++i)
      myMap.insert(std::make_pair(i,i+1));
    mySum=myMap.find(0)->second+myMap.find(1)->second;
    myMaps.push_back(myMap);
  }
  return mySum;
}




2


