std::forward_list<T,Allocator>:: sort
|
void
sort
(
)
;
|
(1) |
(自 C++11 起)
(自 C++26 起为 constexpr) |
|
template
<
class
Compare
>
void sort ( Compare comp ) ; |
(2) |
(自 C++11 起)
(自 C++26 起为 constexpr) |
对元素进行排序并保持等价元素的顺序。如果抛出异常, * this 中元素的顺序是未指定的。
不会使任何引用或迭代器失效。
目录 |
参数
| comp | - |
比较函数对象(即满足
Compare
要求的对象),当第一个参数
小于
(即按顺序排在
之前
)第二个参数时返回
true
。
比较函数的签名应等价于如下形式: bool cmp ( const Type1 & a, const Type2 & b ) ;
虽然签名不需要包含
const
&
,但函数不得修改传递给它的对象,且必须能够接受所有(可能为 const 的)
|
| 类型要求 | ||
-
Compare
必须满足
Compare
的要求。
|
||
复杂度
给定 N 为 std:: distance ( begin ( ) , end ( ) ) :
注释
std::sort
需要随机访问迭代器,因此不能用于
forward_list
。此函数与
std::sort
的不同之处在于:它不要求
forward_list
的元素类型可交换,会保留所有迭代器的值,并执行稳定排序。
示例
#include <functional> #include <iostream> #include <forward_list> std::ostream& operator<<(std::ostream& ostr, const std::forward_list<int>& list) { for (const int i : list) ostr << ' ' << i; return ostr; } int main() { std::forward_list<int> list{8, 7, 5, 9, 0, 1, 3, 2, 6, 4}; std::cout << "初始状态: " << list << '\n'; list.sort(); std::cout << "升序排列: " << list << '\n'; list.sort(std::greater<int>()); std::cout << "降序排列:" << list << '\n'; }
输出:
初始状态: 8 7 5 9 0 1 3 2 6 4 升序排列: 0 1 2 3 4 5 6 7 8 9 降序排列: 9 8 7 6 5 4 3 2 1 0
参阅
|
反转元素的顺序
(公开成员函数) |