std list 排序

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

http://m.blog.youkuaiyun.com/article/details?id=37738601


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

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


std::list has a built-in sort method that you need to use since std::sort only works with random access iterators, whereas std::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());

### C++ 中 `std::list` 排序 对于 `std::list<T>` 容器,在 C++ 标准库中提供了直接对其进行排序的功能。可以利用成员函数 `sort()` 对链表内的元素进行排序操作[^3]。 此成员函数有两种重载形式: - 不带参数版本会使用 `<` 运算符来比较两个元素; - 带有一个自定义比较谓词作为参数的版本允许用户指定不同的排序准则。 下面给出一段简单的代码示例展示如何对整数类型的双向链表执行升序排列以及降序排列: ```cpp #include <iostream> #include <list> void printList(const std::list<int>& lst) { for (const auto& elem : lst) std::cout << elem << " "; std::cout << "\n"; } int main() { // 创建并填充一个包含随机数值的小型列表 std::list<int> numbers = {7, 2, 9, 4}; // 输出原始数据序列 std::cout << "Original list:\t\t"; printList(numbers); // 使用默认方式(即从小到大)对列表进行排序 numbers.sort(); // 展示经过升序处理后的结果 std::cout << "Sorted ascendingly:\t"; printList(numbers); // 自定义比较规则实现从大到小排序 numbers.sort([](int a, int b){return a > b;}); // 显示最终按照降序排列的结果 std::cout << "Sorted descendingly:\t"; printList(numbers); return 0; } ``` 这段程序首先初始化了一个含有四个不同整数值得 `std::list<int>` 实例对象;接着调用了无参版 `sort()` 方法完成自然顺序下的增序调整工作;最后借助带有 lambda 表达式的有参版实现了相反方向上的重新安排过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值