std list 排序

来源:互联网 发布:网络机顶盒破解 编辑:程序博客网 时间:2024/06/05 20:42

http://stackoverflow.com/questions/2432857/sort-list-using-stl-sort-function

http://m.blog.csdn.net/article/details?id=37738601


The standard algorithm std::sort requires random access iterators, whichstd::list<>::iterators are not (list iterators are bidirectional iterators).

You should use the std::list<>::sort member function.


std::list has a built-insort method that you need to use since std::sort only works with random access iterators, whereasstd::list::iterator merely belongs to the bidirectional iterator class of iterators.


定义排序函数:

方法1:声明外部比较函数

bool Less(const Student& s1, const Student& s2){return s1.name < s2.name; //从小到大排序}std::sort(sutVector.begin(), stuVector.end(), Less);

注意:比较函数必须写在类外部(全局区域)或声明为静态函数

当comp作为类的成员函数时,默认拥有一个this指针,这样和sort函数所需要使用的排序函数类型不一样。

否则,会出现<unresolved overloaded function type>错误

方法2:重载类的比较运算符

bool operator<(const Student& s1, const Student& s2){    return s1.name < s2.name; //从小到大排序}std::sort(sutVector.begin(), stuVector.end());


方法3:声明比较类
struct Less{    bool operator()(const Student& s1, const Student& s2)    {        return s1.name < s2.name; //从小到大排序    }};std::sort(sutVector.begin(), stuVector.end(), Less());

0 0