Namespaces
Variants

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。

比较函数的签名应等价于如下:

bool cmp(const Type1& a, const Type2& b);

虽然签名不必有 const&,但函数不能修改传递给它的对象,并且必须能够接受(可有 const 限定的)类型 Type1 和 Type2 的所有值,无论其值类别如何(因此 Type1& 是不允许的,Type1 也是不允许的,除非 Type1 移动等价于复制(自 C++11 起))。
类型 Type1 和 Type2 必须使得类型 <T,Allocator>::const_iterator 的对象可以被解引用并能隐式转换为它们两者。 ​

类型要求
-
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]

参阅

移除连续重复元素
(公开成员函数)