C++里的优先级队列

它是一个模板类:

template ,  class Compare = less > class priority_queue;

默认情况下是 max heap, 默认的比较函数是 std::less.

如果需要 min heap,或者是处理自定义的数据类型,需要提供定制的 比较函数。

priority_queue 的实现使用了 std::make_heap, std::push_heap, std::pop_heap.

在实现自定义的比较函数的时候,可以参考下面的提示:

std::make_heap

default (1)
template   void make_heap (RandomAccessIterator first, RandomAccessIterator last);
custom (2)
template   void make_heap (RandomAccessIterator first, RandomAccessIterator last,                  Compare comp );

Make heap from range

Rearranges the elements in the range [first,last) in such a way that they form a heap.

A heap is a way to organize the elements of a range that allows for fast retrieval of the element with the highest value at any moment (with pop_heap), even repeatedly, while allowing for fast insertion of new elements (with push_heap).

The element with the highest value is always pointed by first. The order of the other elements depends on the particular implementation, but it is consistent throughout all heap-related functions of this header.

The elements are compared using operator< (for the first version), or comp (for the second): The element with the highest value is an element for which this would return false when compared to every other element in the range.

The standard container adaptor priority_queue calls make_heap, push_heap and pop_heap automatically to maintain heap properties for a container.

https://cplusplus.com/reference/algorithm/make_heap/

你可能感兴趣的:(c++,前端)