简体   繁体   中英

the Comparison Functions in C++

I am currently learning STL in C++. And I was looking at references on a program I'm coding. It is using priority queue with a custom object.

struct Foo
{
    std::list<int> path;
    int cost;
    bool operator>(const Foo& rhs) const
    {
        return cost > rhs.cost;
    }
};

class mycomparison
{
public:
    bool operator() (Foo p1, Foo p2) const{
        return (p1>p2);
    }
};

priority_queue<Foo,vector<Foo>,mycomparison> myPQ;

The objects in the priority queue is prioritized for ones with lower cost. I know that you are able to define custom comparators. But I'm not sure why there is an overloaded operator in the struct, and a custom one in class mycomparison, which is used in the priority queue. If I removed the overloaded operator in the struct, it refuses to run.

If someone would please explain to me the use of both code, the relations, how it affects one another, it would be much appreciated!

Thank you.

std::priority_queue uses std::less<T> as the default comparator.

If and when that is not appropriate, as in your case, you have to define a custom comparator or use another comparator that is appropriate for your need.

The implementation details of the operator() function of the comparator is entirely up to you.

Do you need the operator> function in Foo ? Certainly not. You could have used:

class mycomparison
{
  public:
    bool operator() (Foo p1, Foo p2) const{
        return (p1.cost > p2.cost);
    }
};

That could have obviated the need to implement Foo::operator> .

However, using return (p1 > p2) keeps the abstractions in the right place. The details of what p1 > p2 means is best left up to Foo .

BTW, you could have used:

std::priority_queue<Foo, std::vector<Foo>, std::greater<Foo>> myPQ;

That would have made mycomparison unnecessary.

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