[C++] Vector Sort

#include <algorithm>

  • 利用sort就可以了
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。

  • Or you can override the < operator in MyStruct
struct MyStruct
{
    int key;
    std::string stringValue;
    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}

    bool operator < (const MyStruct& str) const {
        return (key < str.key);
    }
};

Using this method means you can simply sort the vector as follows:

std::sort(vec.begin(), vec.end());

 

References:

  1. http://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects
  2. Vincent’s blog
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s