Search code examples
c++priority-queueheap

C++ reverse a priority queue in place


Hi I was wondering if given a std::priority_queue is there are a way to change the heap order from min heap to max heap and vice versa? And I'm not talking about defining a priority queue with greater, what I mean is we already have a priority_queue with some elements.

I would basically want to print elements in reversed order from priority queue while popping.

Now I'm aware that the elements could be loaded up to a stack for example, and then popped from it, that would change the order, but I would like to do it in-place, without using additional memory, or writing my own heap implementation for that matter.

Is there a way to do it?

Example:

std::priority_queue<int> pq{};

pq.push(1);
pq.push(2);
pq.push(3);

while(!pq.empty()){

   std::cout << pq.top();
   pq.pop(); //this would print 321, but I would simply like 123, reversed.
   //but don't change the declaration of the priority_queue. Reverse it when   it has its elements inside of it.

}

Solution

  • You have tagged the question with . This a great hint, why don't use it instead of the priority queue?

    std::vector<int> pq{};
    
    pq.push_back(1);
    pq.push_back(2);
    pq.push_back(3);
    
    // possibly first sort order
    std::make_heap(pq.begin(), pq.end(), std::less<>{});
    
    // ...
    
    // Reorder
    std::make_heap(pq.begin(), pq.end(), std::greater<>{});
    
    while(!pq.empty()) {
      std::pop_heap(pq.begin(), pq.end(), std::greater<>{});
      std::cout << pq.back();
      pq.pop_back();
      // The loop will print 123
    }
    

    You can change a compare function in a heap with remaking it at any time.