C++ List 库 - sort() 函数
描述
C++ 函数 std::list::sort() 按升序对列表的元素进行排序。 保留相等元素的顺序。它使用 operator< 进行比较。
声明
以下是 std::list::sort() 函数形式 std::list 头的声明。
C++98
void sort();
参数
None
返回值
None
异常
此成员函数从不抛出异常。
时间复杂度
线性,即 O(n)
示例
以下示例显示了 std::list::sort() 函数的用法。
#include <iostream>
#include <list>
using namespace std;
int main(void) {
list<int> l = {1, 4, 2, 5, 3};
cout << "Contents of list before sort operation" << endl;
for (auto it = l.begin(); it != l.end(); ++it)
cout << *it << endl;
l.sort();
cout << "Contents of list after sort operation" << endl;
for (auto it = l.begin(); it != l.end(); ++it)
cout << *it << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Contents of list before sort operation 1 4 2 5 3 Contents of list after sort operation 1 2 3 4 5

