Reputation: 485
Suppose that I have a custom struct
struct custom
{
int quantity;
double price;
}
and a priority queue of custom objects:
std::priority_queue<custom, std::vector<custom>, some_custom_comparer_t> pq{...}
The some_custom_comparer_t
will only sort custom
based on price only and not quantity. Is there any way to make it so I can change the quantity
of the custom
object at the top of the priority queue
?
I understand that I won't be able to change the price because the STL container does not allow for adjusting the keys of of the priority queue, but in this case, I want the code to recognize that the quantity
variable is not a key and allow me to modify it.
So far, my solution is to pop it off, adjust the quantity, and push it back in.
Upvotes: 0
Views: 678
Reputation: 63735
Make the quantity mutable
. A mutable member of a class may be modified, even in the context of a const
class instance.
struct custom
{
mutable int quantity;
double price;
};
So far, my solution is to pop it off, adjust the quantity, and push it back in.
Now you can just do:
sq.top().quantity = new_quantity;
Upvotes: 2