3

I have an object class that stores a database record. There is also a comparison class that can take in two of these records and an additional object that describes how the ordering should be done. I need to use these two classes with a priority queue to merge the records. From what I can tell, I can only give a comparison function that takes 2 arguments to the priority_queue. What is the best way to go about using this 3 argument comparator with the priority queue?

    priority_queue <Record, vector<Record>, Comparison(RecordA, RecordB, SortOrderObject)> pq;

2 Answers 2

6

Make a function object containing the extra information, either using boost::bind, std::bind, or by hand, then pass that object into the priority queue. Here's a by-hand version:

class my_compare {
  SortOrder so;
  public:
  my_compare(const SortOrder& so): so(so) {}
  bool operator()(const Record& a, const Record& b) const {
    return comparison(a, b, so);
  }
};

Then pass my_compare as the template argument to priority_queue, and pass my_compare(sort_order) as the comparator in the queue's constructor.

10
  • The question talks about a function, but i always found more pleasant to code, if the comparation are in the class.
    – Gareve
    Mar 7, 2011 at 1:58
  • Don't you need to define operator< instead of operator() ? Mar 7, 2011 at 2:01
  • @Gareve: It is also faster to use an object, since you don't have a call through a function pointer like if you passed in a function directly. Mar 7, 2011 at 2:01
  • 1
    @DasBoot: No -- the comparator is a function object. If you have my_compare c, you compare a and b using c(a, b). Mar 7, 2011 at 2:02
  • 2
    The object's function definition is encoded into its type (i.e., the call is to a known, named function, not a function pointer), allowing for the call to be inlined and things like that. Mar 7, 2011 at 2:13
1

One way would to make the Comparison a template that takes the SortOrderObject as a parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.