I'm trying to create a priority queue with a custom comparator:
std::priority_queue<int, std::vector<int>, MyComparator> pq;
My problem is that MyComparator has a method that stores additional state. Because MyComparator is copied to the priority queue (as far as I can tell), there's no way for me to call this method on the MyComparator instance held by the priority queue. Is there any way to either:
Comparison objects used in STL containers as well as predicates used in STL algorithms must be copyable objects and methods and algorthims are free to copy these functions however they wish.
What this means is that if your comparison object contains state, this state must be copied correctly so you may need to provide a suitable copy constructor and copy assignment operator.
If you want your comparison object to containt mutable state then the problem is more complex as any copies of your comparison object need to share the mutable state. If you can maintain the state as a separate object then you can have your comparison objects keep a pointer to this external state; if not you will probably find that you need shared ownership of the common state so you will probably require something like tr1::shared_ptr
to manage this.
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