命名空间
变体
操作

std::list<T,Allocator>::sort

来自 cppreference.cn
< cpp‎ | 容器‎ | list
 
 
 
 
void sort();
(1)
template< class Compare >
void sort( Compare comp );
(2)

对元素进行排序并保持等价元素的顺序。所有引用或迭代器都不会失效。

1) 元素使用 operator< 进行比较。
2) 元素使用 comp 进行比较。

如果抛出异常,*this 中元素的顺序未指定。

目录

[编辑] 参数

comp - 比较函数对象(即满足 Compare 要求的对象),如果第一个参数“小于”(即“排在第二个参数之前”)第二个参数,则返回 true

比较函数的签名应等效于以下内容

bool cmp(const Type1& a, const Type2& b);

虽然签名不需要包含 const&,但该函数不得修改传递给它的对象,并且必须能够接受 Type1Type2 类型(可能为 const)的所有值,无论其 值类别如何(因此,不允许使用 Type1&,除非对于 Type1 移动等同于复制,否则也不允许使用 Type1(C++11 起))。
类型 Type1Type2 必须使得类型为 list<T,Allocator>::const_iterator 的对象可以被解引用,然后隐式转换为这两种类型。​

类型要求
-
Compare 必须满足 Compare 的要求。

[编辑] 返回值

(无)

[编辑] 复杂度

给定 N 作为 size()

1) 大约 N·log(N) 次使用 operator< 的比较。
2) 大约 N·log(N) 次比较函数 comp 的应用。

[编辑] 注意

std::sort 需要随机访问迭代器,因此不能与 list 一起使用。此函数也与 std::sort 不同,它不要求 list 的元素类型可交换,保留所有迭代器的值,并执行稳定排序。

[编辑] 示例

#include <functional>
#include <iostream>
#include <list>
 
std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list)
{
    for (const int i : list)
        ostr << ' ' << i;
    return ostr;
}
 
int main()
{
    std::list<int> list{8, 7, 5, 9, 0, 1, 3, 2, 6, 4};
    std::cout << "initially: " << list << '\n';
 
    list.sort();
    std::cout << "ascending: " << list << '\n';
 
    list.sort(std::greater<int>());
    std::cout << "descending:" << list << '\n';
}

输出

initially:  8 7 5 9 0 1 3 2 6 4
ascending:  0 1 2 3 4 5 6 7 8 9
descending: 9 8 7 6 5 4 3 2 1 0

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 1207 C++98 迭代器和/或引用是否会失效不明确 保持有效

[编辑] 另请参阅

反转元素的顺序
(public 成员函数) [编辑]