简体   繁体   中英

How can I use a comparison function with more than 2 arguments with a c++ priority queue?

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;

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.

一种方法是使比较成为将SortOrderObject作为参数的模板。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM