C++ 列表库 - sort() 函数



描述

C++ 函数 std::list::sort() 用于按升序对列表中的元素进行排序。相等元素的顺序保持不变。它使用operator<进行比较。

声明

以下是来自 std::list 头文件的 std::list::sort() 函数的声明。

C++98

void sort();

参数

返回值

异常

此成员函数从不抛出异常。

时间复杂度

线性,即 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
list.htm
广告

© . All rights reserved.