The std::priority_queue pattern provides all the properties of the heap. Constant maximum or minimum extraction (depending on how the elements are compared) and a logarithmic time insertion. It can be found in the header file <queue> .
By default, priority_queue is the maximum heap.
int numbers[11] = { 0, 9, 3, 4, 8, 12, 2, 11, 10, 1, 5 }; std::priority_queue<int> myheap(numbers, numbers + 11); std::cout << "biggest " << myheap.top() << std::endl; // 12 myheap.pop(); std::cout << "biggest " << myheap.top() << std::endl; // 11 myheap.push(6); std::cout << "biggest " << myheap.top() << std::endl; // 11 myheap.push(13); std::cout << "biggest " << myheap.top() << std::endl; // 13
Here is an example of creating a mini-heap:
std::priority_queue< int, std::priority_queue<int>::container_type, std::greater<int> >;
To implement the streaming median algorithm, an approach similar to this:
- create the maximum heap for items that are smaller than the median
- create a mini-heap for items that are larger than median
- when you click new items in a bunch
- Decide which heap to insert and click there.
- if one of the heap sizes is more than 1 larger than the other heap, then place the majority and place this element in a smaller
Then the median is either the top of the larger heap or the middle peak of both heaps.
If you think you need to manually manage the heap, C++ provides algorithms that let you do this in your own random access data structure.
std::make_heap - heapify the region specified by the end points of the iteratorstd::push_heap - assumes that the first elements of N-1 are already a heap and add the Nth element to the heapstd::pop_heap - puts the first element in the region at the last position and regenerates the region, but leaving only the last element
source share