list和vector默认的排序准则是升序排序,我们可以通过传递自定义参数的方式,指定他的排序准则。通常有两种指定方式:
(1)通过传递比较函数
(2)传递函数对象
/*************************************************************************
> File Name: listSort.cpp
> Author: ltf
> Created Time: Thu 31 Mar 2016 11:46:31 AM CST
************************************************************************/
#include<iostream>
#include<list>
typedef struct
{
int x;
int y;
}Node;
using namespace std;
//按Y降序,函数
bool sortFunction(const Node &v1,const Node &v2)
{
if(v1.y > v2.y)
return true;
else
return false;
}
//按Y升序,函数对象
struct sortObject{
bool operator()(const Node &v1,const Node &v2) //重载函数操作符
{
if(v1.y < v2.y)
return true;
else
return false;
}
};
void print(list<Node> &test)
{
for(const auto & elem:test)
{
cout << "x:" << elem.x << " y:" << elem.y << endl;
}
}
int main(void)
{
list<Node> test;
Node tmp;
for(int i=0;i<3;i++)
{
tmp.x = i;
tmp.y = 3-i;
test.push_back(tmp);
}
print(test);
test.sort(sortObject()); //函数对象
cout << "after sorted 1(Y ascending):" <<endl;
print(test);
test.sort(sortFunction); //传递函数指针
cout << "after sorted 2(Y descending):" <<endl;
print(test);
return 0;
}