Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL priority_queue copies comparator class

Tags:

c++

stl

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:

  • get access to the MyComparator instance held by the priority queue, or:
  • somehow pass the original MyComparator instance in by reference
like image 824
thekidder Avatar asked Dec 22 '22 06:12

thekidder


1 Answers

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.

like image 153
CB Bailey Avatar answered Jan 07 '23 12:01

CB Bailey