◐ Shell
clean mode source ↗

std::hive<T,Allocator>::sort - cppreference.com

From cppreference.com

template< class Compare = std::less<T> >
void sort( Compare comp = Compare() );
(since C++26)

Sorts the elements. May allocate. Elements are compared using comp. The order of equivalent elements is not preserved.

References, pointers, and iterators referring to elements in *this, as well as the past-the-end iterator, may be invalidated.

T should be MoveInsertable into hive, MoveAssignable, and Swappable. Otherwise, the behavior is undefined.

Parameters

comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than (i.e. is ordered before) the second.

The signature of the comparison function should be equivalent to the following:

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

While the signature does not need to have const&, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) Type1 and Type2 regardless of value category (thus, Type1& is not allowed, nor is Type1 unless for Type1 a move is equivalent to a copy(since C++11)).
The types Type1 and Type2 must be such that an object of type <T,Allocator>::const_iterator can be dereferenced and then implicitly converted to both of them. ​

Type requirements
-Compare must meet the requirements of Compare.

Complexity

N·log(N) applications of the comp, where N is size().

Exception

If an exception is thrown, the order of elements in *this is unspecified.

Notes

std::sort and ranges::sort require random access iterators and so cannot be used with hive.

Example

#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);
}

Output:

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]

See also

removes consecutive duplicate elements
(public member function) [edit]