简体   繁体   中英

Shrinking a std::priority_queue

Given a std::priority_queue to which elements are being added faster than they are being removed by the usual process of repeatedly popping the best element, so that the program is going to run out of memory unless something is done,

Is there any way to throw away the worst half of the elements, while leaving the best half to be processed one at a time as normal?

Clearly not, since the interface to a std::priority_queue is so extremely limited. You could implement your own priority queue that will let you do this using make_heap, push_heap and pop_heap (this is how std::priority_queue is implemented) and implementing your own function to remove the worst half of the elements.

There isn't a direct way. But a binary heap doesn't really support that operation anyways.

But it's not hard to indirectly do so:

  • Create a temporary empty priority queue
  • Swap the main and temporary queues
  • Enter a loop that pops from the temporary and pushes to the main
  • Stop when you're happy with the number of copied elements
  • Destroy the temporary queue.

The std::priority_queue is a 2-heap and as such only partially ordered. The data-structure is not useful to locate the best half of the elements differently than extracting them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM