Re: [心得] cached hash value

看板C_and_CPP (C/C++)作者 (三十億人的世界)時間16年前 (2009/03/23 02:00), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串2/2 (看更多)
我的想法是 1 如果要省的是算hash value 的時間,那要那每次算的時候都先查表 2 unordered_map 第三個 template parameter 可以給定自定的hash object 3 functor 的強項就可以保有內部資料 所以我的作法是 template<typename key_type> class my_hash { public: my_hash::my_hash(){}; size_t operator()(const key_type& key) const { map<int, size_t>::iterator iter; if((iter = hashval.find(key)) != hashval.end()) return iter->second; else { hashval[key] = hashfun(key); return hashval[key]; } } private: mutable map<key_type, size_t> hashval; hash<key_type> hashfun; }; //main function unordered_map<string, int, my_hash<string> > dict<10, my_hash<string>()); 這樣是你想要的東東嗎? ps: 關於buckets 的值,10 是 gnu c++ library 的預設值,VC++ 是 8 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.124.160.118

03/23 02:07, , 1F
不過比來比去真的有算hash快嘛?疑問
03/23 02:07, 1F

03/23 08:19, , 2F
你這樣光是在map中查值都可能比算hash還慢
03/23 08:19, 2F

03/23 09:37, , 3F
後來想想我也是這麼覺得,很蠢...
03/23 09:37, 3F
文章代碼(AID): #19ndpBWM (C_and_CPP)
文章代碼(AID): #19ndpBWM (C_and_CPP)