2009-03-17

vector 排序

vector排序,只要 #include <algorithm>
利用sort這function就可以了。

簡單的vector

vector <int> temp;
temp.push_back(2);
temp.push_back(4);
temp.push_back(6);

sort(temp.begin(),temp.end());

結果就是由小排到大。
可是如果 vector 存的是 struct ,就得要多寫一個比較的function


typedef struct Freqamp{
double freq;
double amp;
}FREQAMP;

bool struct_cmp_by_freq(FREQAMP a, FREQAMP b)
{
return a.freq < b.freq;
}

main()
{
vector <FREQAMP> temp;
FREQAMP freqAMP;

freqAMP.freq = 330;
freqAMP.amp = 117.56;
temp.push_back(freqAMP);

freqAMP.freq = 450;
freqAMP.amp = 99.56;
temp.push_back(freqAMP);

freqAMP.freq = 110;
freqAMP.amp = 106.56;
temp.push_back(freqAMP);

sort(temp.begin(),temp.end(), struct_cmp_by_freq);
}


就可以針對其中一項下去排序,不過要注意 sort 是當 compare 為 false 時做swap。

3 則留言:

  1. 咦?vector可以不用指定容器的型態喔?我以為在宣告時一定要寫成:
    vector< int > temp;
    而非只有
    vector temp;

    我很好奇沒有指定型態的話,下面這樣寫會不會錯。

    vector temp;
    FREQAMP freqAMP;
    ...
    temp.push_back(2);
    temp.push_back(freqAMP);
    至甚再來個
    sort(temp.begin(),temp.end());

    最後一問,就是這個sort可適用在別種 STL 嗎?因為 list 似乎自己有個member function 叫 sort ...

    回覆刪除
  2. 貼在文章裡面有指定型態
    不過我忘了把<>這兩個符號用編碼的方式表示出來
    所以他就認為是html的tag

    謝謝你的提醒啦
    已經改過來了

    至於這個sort好像無法用在list 的sort
    這個網址提到
    Note that sort() will only work with random access iterators. So you cannot use sort() on the iterators of a 「list」 (linked list). Instead, you should use list's own sort method to sort it instead.

    回覆刪除
  3. 恩喔,了解。我翻了下msdn,random access iterators還有deque,其他容器也有各自的功能感覺很有趣。

    該不會又要買一本 Effective STL 吧..orz

    回覆刪除