我有一个 stl::list 包含 Widget 类对象。它们需要根据 Widget 类中的两个成员进行排序。
为了使排序工作,必须定义一个比较两个 Widget 对象的小于比较器。似乎有无数种方法可以做到这一点。据我所知,一个人可以:
一种。在类中定义一个比较运算符重载:
bool Widget::operator< (const Widget &rhs) const
湾。定义一个带有两个 Widget 的独立函数:
bool operator<(const Widget& lhs, const Widget& rhs);
然后让 Widget 类成为它的朋友:
class Widget {
// Various class definitions ...
friend bool operator<(const Widget& lhs, const Widget& rhs);
};
C。定义一个仿函数,然后在调用排序函数时将其作为参数包含在内:
class Widget_Less :
public binary_function<Widget, Widget, bool> {
bool operator()(const Widget &lhs, const Widget& rhs) const;
};
有人知道哪种方法更好吗?特别是我很想知道我应该做 1 还是 2。我搜索了 Scott Meyer 的《Effective STL》一书,但不幸的是,它对此没有什么可说的。
感谢你的回复。