Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make STL's priority_queue fixed-size

Tags:

c++

std

stl

I am creating a simple game and I use std::priority_queue for giving commands to squads (every squad has a priority_queue<command>).

Every 20 seconds a bot analyses the situation and sends commands to the priority_queue.

How can I make the priority_queue fixed-size, for example, set the size to 10? The desired effect is that when the maximum is reached, if I add 2 new commands to the queue, 2 existing commands with the lowest priority are automatically removed.

like image 922
Damir Avatar asked Jul 21 '12 08:07

Damir


People also ask

How do I set the size of a queue in C++?

queue::size() is an inbuilt function in C++ STL which is declared in <queue> header file. queue::size() is used to check whether the size of the associated queue container. This function returns an unsigned int value, i.e the size of the queue container, or the number of elements present in a queue container.

How is priority queue size determined?

PriorityQueue. size() method is used to get the size of the PriorityQueue or the number of elements present in the PriorityQueue. Parameters: This method does not takes any parameter. Return Value: The method returns the size or the number of elements present in the PriorityQueue.

How do you define priority queue size in C++?

CPP. size() function is used to return the size of the priority queue container or the number of elements in the container.

How do I know if my priority queue is not empty?

Check if the Priority Queue is Empty We use the empty() method to check if the priority_queue is empty. This method returns: 1 (true) - if the priority queue is empty. 0 (false) - if the priority queue is not empty.


1 Answers

Aryabhatta's answer of another question applies to this question.

You use a max-heap.

Say you have an N element heap (implemented as an array) which contains the N smallest elements seen so far.

When an element comes in you check against the max (O(1) time), and reject if it is greater.

Iteration mentioned by several earlier comments is unnecessary.

like image 125
Zhichang Yu Avatar answered Oct 04 '22 02:10

Zhichang Yu