简体   繁体   中英

Why custom comparator functions are passed in Class or Struct?

I am writing a priority queue that has its own comparator function. Every where I see following implementation and not able to figure out what's the rationale behind defining comparator function in class or struct?

struct CompareHeight { 
    bool operator()(pair<int, int> const p1, pair<int, int> const p2) 
    { 
        if(p1.first == p2.first)
            return p1.second > p2.second; 
        return p1.first < p2.first; 
    } 
}; 

int main(){
    priority_queue<pair<int, int >, vector<pair<int,int> >, CompareHeight> p;
}

Edit 1 - why use class or struct directly define a comparator function just like main function and used it?

Why custom comparator functions are passed in Class or Struct?

Classes are often used rather than the alternative - function pointer that is - because doing so is potentially faster. A function pointer is inherently a form of runtime polymorphism. It is sometimes impossible, or just too difficult for an optimiser to determine at call time, what function is going to be called.

By contrast, the member function operator overload of a class is known at compile time because the class is known at compile time. At minimum, there is advantage of not having to indirect through a pointer to make the call. In some cases, this may even open door to inline expansion and through that, other optimisations.

Function objects also have the advantage of being able to store data across their invocations, although there isn't always need to take advantage of that possibility.


PS It is often better to generate the function object class using a lambda instead of writing it explicitly.

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