简体   繁体   中英

std::priority_queue different comparisons

I want to construct three different priority_queue 's that hold a class Thing and then sort each one differently by values that are held by the Thing . I know that I can define an operator method either internally, or a friend to the object, but is there a way to have it use different test method(s)? How do I tell it to use that method instead of the operator method? And how would the parameter list differ from creating an operator overload?

Like most STL containers, the priority_queue accepts a Compare class in its template arguments .

struct MyCompare1 {
  bool operator()(const Thing& t1, const Thing& t2) {
    // your logic here
  }
};

std::priority_queue<Thing, std::vector<Thing>, MyCompare1> my_queue;

You can pass a custom comparator type that will be used instead of the default. This is a template parameter of the priority_queue .

You can specify your comparison function as the third parameter when defining the priority_queue . Note that the second parameter is the underlying container type, typically std::vector .

std::priority_queue<Thing> pq1;
std::priority_queue<Thing, std::vector<Thing>, std::greater<Thing> > pq2;
std::priority_queue<Thing, std::vector<Thing>, [your comparator here] > pq3;

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