• 文章
  • 動態地對鍵和值進行排序
釋出
2014年9月24日(最後更新:2014年10月30日)

動態地對鍵和值進行排序

評分:3.5/5(359票)
*****
嗯,你可能在程式設計生涯中遇到過這個問題,或許也已經知道了答案。這個問題是關於 std::map 或 std::multimap 的,它們都是一種特殊型別的容器,可以透過比較函式指標(或像 std::less 這樣的內建函式)對專案進行排序。它們在你插入新專案時就會排序,這當然非常方便,因為你不想每次需要時都呼叫一個排序函式!實際上,你永遠不需要對 map 或 multimap 顯式呼叫任何排序函式,因為它已經排好序了!現在,我的問題來了——
比方說,我有一個像這樣的 map ——
D - 1
D - 2 
B - 3
A - 4

現在我需要像這樣對它們進行排序 ——
A - 4 
B - 3 
D - 2
D - 1
排序的解釋是這樣的——首先,第一個元素(A、B、D)將按升序排列 A --> B --> D,而不考慮第二個元素;其次,如果第一個元素相等(這裡有兩個D),那麼它們將按其對應的第二個元素的降序排列。
使用 std::multimap 只能完成第一部分的排序,所以我利用了模板和繼承。這是程式碼——
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <utility>
#include <set>

using namespace std;

template <class _A, class _B, class _Compare=less<_A> >
class MMap : public set < pair< _A, _B >, _Compare >
{
        public :
                MMap():set< pair< _A, _B >, _Compare >(){};
                ~MMap(){};
};

template< typename InPair >
struct MMapComp{
        bool operator() (InPair a , InPair b){
                if( a.first == b.first ) return a.second > b.second;
                else
                        return a.first < b.first;
        }
};

int main(int argc, char ** argv)
{
        MMap<char,int,MMapComp< pair<char , int > > > test;

        test.insert(make_pair('D',1));
        test.insert(make_pair('D',2));
        test.insert(make_pair('B',3));
        test.insert(make_pair('A',4));

        for( MMap<char,int >::iterator it = test.begin(); it != test.end(); it++ )
                cout << (*it).first << "\t" << (*it).second << endl;
        return 0;
}

這是輸出結果——

A	4
B	3
D	2
D	1

好吧,我為我沒有寫文件的程式碼道歉 :) 但它其實並不難讀,是嗎?