一、 #include <iostream> #include <vector> #include <algorithm> using namespace std; struct StructTerm { int TermID; float Occurency; }; typedef vector<StructTerm> TERMS; class Comparer { public: bool operator () (const StructTerm & va1, const StructTerm & va2) { return va1.Occurency > va2.Occurency; } }; int main() { TERMS terms; StructTerm s; s.TermID = 1; s.Occurency = 0.8; terms.push_back(s); s.TermID = 2; s.Occurency = 0.6; terms.push_back(s); s.TermID = 2000; s.Occurency = 0.68; terms.push_back(s); sort(terms.begin(), terms.end(), Comparer()); for(int i = 0; i < terms.size(); ++i) { cout << terms[i].TermID << " "; } cout << endl; } 一般都是把Comparer 放到StructTerm里面,用的时候用StructTerm::Comparer 二、 #include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std; struct StructTerm { string name; int age; }; bool operator < (const StructTerm & va1, const StructTerm & va2) { return va1.age < va2.age; } class Comparer { public: bool operator () (const StructTerm & va1, const StructTerm & va2) { return va1.name < va2.name; } }; int main() { vector<StructTerm> term; StructTerm s; s.name = "ofdspo"; s.age = 2; term.push_back(s); s.name = "jfkdsu"; s.age = 85; term.push_back(s); s.name = "uiofuso"; s.age = 19; term.push_back(s); s.name = "fdserw"; s.age = 20; term.push_back(s); s.name = "rgdsgf"; s.age = 43; term.push_back(s); sort(term.begin(), term.end()); int i; for(i = 0; i < term.size(); ++i) { cout << term[i].name << " " << term[i].age << endl; } cout << endl; sort(term.begin(), term.end(), Comparer()); for(i = 0; i < term.size(); ++i) { cout << term[i].name << " " << term[i].age << endl; } return 0; } 第一种方法为重载<运算符,以前习惯使用的。 第二种方法是使用函数对象,以后尽量使用这个。