C++里的优先级队列

它是一个模板类:

template <class T, class Container = vector<T>,  class Compare = less<typename Container::value_type> > class priority_queue;

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

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

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

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

std::make_heap

default (1)
template <class RandomAccessIterator>  void make_heap (RandomAccessIterator first, RandomAccessIterator last);
custom (2)
template <class RandomAccessIterator, class Compare>  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/

猜你喜欢

转载自blog.csdn.net/CaspianSea/article/details/132013775