C++ List 库 - sort() 函数
描述
C++ 函数 std::list::sort() 对列表的元素进行排序。 保留相等元素的顺序。 它使用比较功能来比较值。
声明
以下是 std::list::sort() 函数形式 std::list 头的声明。
C++98
template <class Compare> void sort (Compare comp);
参数
comp − 返回布尔值的比较函数对象。 它有以下原型。
bool cmp(const Type1 &ar1, const Type2 &arg2);
返回值
None
异常
此成员函数从不抛出异常。
时间复杂度
线性,即 O(n)
示例
以下示例显示了 std::list::sort() 函数的用法。
#include <iostream>
#include <list>
using namespace std;
bool comp(int a, int b) {
return (a > b);
}
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;
/* Descending sort */
l.sort(comp);
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 5 4 3 2 1

