C ++中的链排序
在本节中,我们将看到如何使用C++标准库对数组或链表进行排序。在C++中,有多个不同的库可用于不同的目的。排序是其中之一。
C++函数std::list::sort()按升序对列表中的元素进行排序。相等元素的顺序被保留。它使用operator<进行比较。
示例
#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