std::hive<T,Allocator>::sort
来自 zh.cppreference.net
template< class Compare = std::less<T> >
void sort( Compare comp = Compare() );
|
(自 C++26 起) | |
对元素进行排序。可能分配内存。元素通过 comp 进行比较。不会保留等价元素的顺序。
指向 *this 中元素的引用、指针和迭代器,以及尾后迭代器,可能会失效。
T 必须是可移动插入到 hive(MoveInsertable)、可移动赋值(MoveAssignable)和可交换(Swappable)。否则行为未定义。
参数
| comp | - | 比较函数对象(即满足 Compare 要求的对象),当第一个参数true小于(即排序先于第二个参数时返回 true。比较函数的签名应等价于如下:
虽然签名不必有 |
| 类型要求 | ||
-Compare 必须满足 Compare 的要求。
| ||
复杂度
N·log(N) 次 comp 应用,其中 N 为 size()。
异常
如果抛出异常,则 *this 中元素的顺序未指定。
注解
std::sort 和 ranges::sort 要求随机访问迭代器,因此不能与 hive 一起使用。
示例
运行此代码
#include <hive>
#include <functional>
#include <print>
int main()
{
std::hive<int> hive{3, 1, 4, 1, 5, 9, 2, 6, 5};
std::println("Initially: {}", hive);
hive.sort();
std::println("Ascending: {}", hive);
hive.sort(std::greater<int>());
std::println("Descending: {}", hive);
}
输出:
Initially: [3, 1, 4, 1, 5, 9, 2, 6, 5]
Ascending: [1, 1, 2, 3, 4, 5, 5, 6, 9]
Descending: [9, 6, 5, 5, 4, 3, 2, 1, 1]
参阅
| 移除连续重复元素 (公开成员函数) |