Re: [問題] 煩請高手建議一個結構
你最好的解法是 boost::bimap
http://www.boost.org/doc/libs/1_39_0/libs/bimap/doc/html/index.html
次好的是 boost::multi_index
http://www.boost.org/doc/libs/1_39_0/libs/multi_index/doc/index.html
如果我們不管 bimap 或是 multi_index,直接來面對你的問題,
其實你問題的本質就是「分數跟人名的關係」也就是 "relation",
而表達 relation 最簡單的方法就是 pair,
typedef pair<ing, string> relation_type ;
所以理論上我們要維護的是一組 relation,而理想的資料結構就是
set<relation_type> relations ;
但是,我們還需要能夠從右側快速的索引到我們要的 relation,
所以我們還需要另外一個 map 讓我們可以從 value(string) 索引到 relation。
map<string, relation_type> right_idx ;
當我們要插入一筆資料的時候,
我們要把他加到我們的 relation set,
也要把他加入我們的 right indexer。
relation_type data(100, "小明") ;
relations.insert(data) ;
right_idx[data.second] = data ;
當我們要根據 value 刪除一筆資料的時候,
我們先從 right indexer 把這個 relation 檢索出來,
然後就可以從 relation set 裡面把他移除掉,
當然,也要記得把他從 right indexer 移除掉,像這樣……
relation r = right_idx["小明"] ;
relations.erase(r) ;
right_idx.erase("小明") ;
等等!
「幹!還有一個根本上的問題!
我還需要從 left 排序列舉阿!你忘記了!」
沒有問題,因為這個問題打從一開始就已經順手解決了,
還記得我們用來存放 relation 的是什麼嗎?
set<relation> 也就是
set< pair<int, string> >
set 列舉的時候會排序,根據 element 的大小來排,
我們的 element 是 pair,而 STL 標準告訴我們:
pair 的優先順序是先比第一個,再比第二個。
這代表當我們對 relations 列舉的時候,本來就會依照 int 排好。
太巧了,真是撿到的,這一切都是巧合 O_O
--
To iterate is human, to recurse, divine.
遞迴只應天上有, 凡人該當用迴圈. L. Peter Deutsch
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.160.109.187
推
07/03 00:45, , 1F
07/03 00:45, 1F
推
07/03 00:51, , 2F
07/03 00:51, 2F
推
07/03 09:37, , 3F
07/03 09:37, 3F
推
07/03 10:29, , 4F
07/03 10:29, 4F
推
07/03 11:15, , 5F
07/03 11:15, 5F
討論串 (同標題文章)
完整討論串 (本文為第 4 之 4 篇):
2
3
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章