[心得] cached hash value
之前想要繼承 std::string 多增加一個快取的 hash_value 欄位,
這樣在使用 std::unordered 的時候,可以加速查找的效能。
但是經過一些摸索之後證明這是一個愚蠢的念頭,
比較好的做法是設計一個 class 把 std::string 包裝在內部,而不是繼承。
真的開始改 code 之後,發現這也不是一個好念頭,
更好的是設計一個泛型 class,對於任何型別都可以作 hash_value 快取。
像是這樣……
template < class T >
class hashed {
public :
hashed ( const hashed& h ) ;
hashed ( const T& v ) ;
T value () ;
size_t hash_value () ;
private :
T v_ ;
size_t hash_value_ ;
} ;
使用起來是這樣:
int main () {
std::string s = "three"
hashed<std::string> hs ;
hs = s ;
std::unordered<hashed<std::string>, int> umap ;
umap[hs] = 3 ;
std::cout << umap[hs] << std::endl ;
}
美中不足的時候每個被拷貝進去 unordered map 的字串都會多帶一個 hash_value,
其實我們只有在查找的時候才需要快取的 hash value,一旦存進去之後就用不到,
想了一下唯一的解法好像是去繼承 unordered_map,多加一個 find 的覆載…
Iterator find ( const hashed<KeyType>& h ) ;
然後使用 unordered 的時候還是使用沒有包覆的型別
std::unordered<std::string, int> umap ;
std::string s = "three" ;
hashed<string> hs = s ;
umap[s] = 3 ;
std::cout << umap[hs] << std::endl ;
各位大大有沒有建議…
可能我這次又跟上次一樣鬧笑話 orz
--
To iterate is human, to recurse, divine.
遞迴只應天上有, 凡人該當用迴圈. L. Peter Deutsch
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.160.106.44
推
03/21 00:21, , 1F
03/21 00:21, 1F
→
03/21 00:21, , 2F
03/21 00:21, 2F
→
03/21 00:23, , 3F
03/21 00:23, 3F
推
03/21 00:25, , 4F
03/21 00:25, 4F
推
03/21 00:30, , 5F
03/21 00:30, 5F
→
03/21 00:32, , 6F
03/21 00:32, 6F
推
03/21 10:19, , 7F
03/21 10:19, 7F
討論串 (同標題文章)
完整討論串 (本文為第 1 之 2 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章