std::forward_list<T,Allocator>::sort
来自cppreference.com
<tbody>
</tbody>
void sort(); |
(1) | (C++11 起) |
template< class Compare > void sort( Compare comp ); |
(2) | (C++11 起) |
排序元素,并保持等价元素的顺序。不会导致迭代器和引用失效。
1) 用
operator< 比较元素。2) 用
comp 比较元素。如果抛出了异常,那么 *this 中元素的顺序未指定。
参数
| comp | - | 比较函数对象(即满足比较 (Compare) 概念的对象),在第一参数小于(即先 序于)第二参数时返回 true。比较函数的签名应等价于如下:
虽然签名不必有 |
| 类型要求 | ||
-Compare 必须满足比较 (Compare) 。
| ||
返回值
(无)
复杂度
令 N 为 std::distance(begin(), end()):
1) 应用大约 N·log(N) 次
operator< 进行比较。2) 应用大约 N·log(N) 次比较函数
comp。注解
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
参阅
| 反转元素的顺序 (公开成员函数) |