struct p{ int w p(int w):w(w){} } struct cmp { bool operator()(cosnt p & p1, const p & p2)//parameter must be const,or it will be compile error { return p1.w > p2.w;//reverse sort } } int main() { vector<p>obj; for(int i = 0; i< 10; i++){ obj.push_back(p(i)); } sort(obj.begin(),obj.end(),cmp());//here we must use function object cmp() instead of cmp which is a type. } set要使用自定义元素的话要对元素实现<的比较函数。 STL中的容器基本都是使用<符号进行比较。 //compare function object for struct crossroad struct crossroad { int row; int col; crossroad(int r, int c) : row(r), col(c) { } }; struct cmp{ bool operator()(const crossroad & cr1,const crossroad & cr2){ return (cr1.row < cr2.row && cr1.col < cr2.col); } }; set<crossroad,cmp>road; int main(){ road.insert(make_pair(1)); return 0; } 同样的,如果需要用到stl中的sort进行排序,对于自定义类型元素必须定义比较对象。