Re: [STL] Container一問:value可排序的hash_map?

看板C_and_CPP作者 (艾斯寇德)時間14年前 (2010/08/08 04:59), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/3 (看更多)
※ 引述《Aligu1009 (=.=)》之銘言: : 請問有符合以下這些要求的container嗎? : 1. 類似hash_map,有key與value的對應 : 2. 可以對value進行排序 : 我覺得有這樣的container應該蠻合理的,因為這是很常使用的功能 : 但網上搜了搜卻沒找到這樣的container :( : 例子:把一篇文章中所有的字依字數多寡做排列 : 一個直觀的做法就是用hash_map存字與字數的對應 : 然後排序後印出 : 但,hash_map是不能依value做排序的 : 請問有適合這種要求的container嗎?謝謝 定義一個給需要compare的結構的comparator,使得equal是在物件位址相同的情況, 因此使得value相同為less 如果你期待物件具有反查能力,則定義 Obj{ keytype key; valuetype value; } int comparator(const Obj* a, const Obj* b){ const static int resultValue[2]={-1,1}; if(a == b){ return 0; } if( equal(a->value,b->value) ) { return resultValue[ ((int)a-(int)b) > 0 ]; } return resultValue[ greater(a->value,b->value) ]; } 讓HashTable紀錄物件位址, 定義 read only的operator[]為hashtable的get 讓 rw的operator[] 的operator=行為如下 obj = tree.remove( hashtable.get(INPUT) ) write(obj) tree.insert(obj) 因此tree保有順序,只有位址相同才是equal, 在value相同的時候,以物件位址當作大小,否則以value作為大小關係。 那麼可以藉由任何可雜湊的物件當作key,包括字串、字元 用comparable的物件作為value (ex: 字串出現次數) 在你期待印出順序關係時,可以用tree的inorder/iter印出Obj的key,value 因此你可以看到key依照value順序秀出的效果 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.35.210.65 ※ 編輯: sunneo 來自: 114.35.210.65 (08/08 05:04)
文章代碼(AID): #1CNSadVg (C_and_CPP)
文章代碼(AID): #1CNSadVg (C_and_CPP)