gardian06
gardian06

Reputation: 1546

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?

Upvotes: 0

Views: 140

Answers (3)

chrisaycock
chrisaycock

Reputation: 37930

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;

Upvotes: 2

Blastfurnace
Blastfurnace

Reputation: 18652

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;

Upvotes: 0

Puppy
Puppy

Reputation: 146940

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

Upvotes: 0

Related Questions