prashant
prashant

Reputation: 3318

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?

Upvotes: 2

Views: 627

Answers (1)

eerorika
eerorika

Reputation: 238311

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.


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

Upvotes: 4

Related Questions