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。

(繼續閱讀...)