Defining < for STL sort algorithm - operator overload, functor or standalone function?
- by Andy
I have a stl::list containing Widget class objects. They need to be sorted according to two members in the Widget class.
For the sorting to work, I need to define a less-than comparator comparing two Widget objects. There seems to be a myriad of ways to do it. From what I can gather, one can either:
a. Define a comparison operator overload in the class:
bool Widget::operator< (const Widget &rhs) const
b. Define a standalone function taking two Widgets:
bool operator<(const Widget& lhs, const Widget& rhs);
And then make the Widget class a friend of it:
class Widget {
// Various class definitions ...
friend bool operator<(const Widget& lhs, const Widget& rhs);
};
c. Define a functor and then include it as a parameter when calling the sort function:
class Widget_Less :
public binary_function<Widget, Widget, bool> {
bool operator()(const Widget &lhs, const Widget& rhs) const;
};
Does anybody know which method is better? In particular I am interested to know if I should do 1 or 2. I searched the book Effective STL by Scott Meyer but unfortunately it does not have anything to say about this.
Thank you for your reply.