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.
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.
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.
CPP. size() function is used to return the size of the priority queue container or the number of elements in the container.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With