[英]overloaded less than (<) operator for sorting objects in several ways
If a class has overloaded an operator to facilitate sorting its objects by a particular attribute, is there a way to overload the operator again to sort by another attribute? 如果一个类使运算符重载以利于按特定属性对对象进行排序,是否有办法使运算符再次重载以按另一个属性进行排序?
For example, the class below has overloaded operator<
to compare its data member minutes, is there a way to do the same for its data member hours or would I just be better off creating a binary predicate for each sorting criteria? 例如,下面的类重载了
operator<
以比较其数据成员的分钟数,是否有办法对其数据成员的小时数做同样的事情,或者我会为每个排序标准创建一个二进制谓词更好吗? Thanks in advance. 提前致谢。
class PhoneCall {
friend ostream& operator<<( ostream&,const PhoneCall& );
private:
int minutes;
int hours;
public:
PhoneCall(int = 0);
bool operator<(const PhoneCall&);
};
ostream& operator<<(ostream& out, const PhoneCall& p) {
out << "Phone call lasted " << p.minutes << " minutes" << endl;
return out;
}
PhoneCall::PhoneCall(int ct) {
minutes = ct;
}
bool PhoneCall::operator<(const PhoneCall& p) {
bool less = (minutes < p.minutes)? true: false;
return less;
}
You can also present extra friend functions that provide alternative sorting methods, and in c++11 you can define them inplace: 您还可以提供其他朋友功能来提供其他排序方法,在c ++ 11中,您可以就地定义它们:
class PhoneCall {
friend ostream& operator<<( ostream&,const PhoneCall& );
private:
int minutes;
int hours;
public:
PhoneCall(int = 0);
bool operator<(const PhoneCall&);
friend bool LessTime(const PhoneCall& L, const PhoneCall& R)
{ return L.minutes+L.hours*60 < R.minutes+R.hours*60; }
};
std::vector<PhoneCall> calls;
std::sort(calls.begin(), calls.end(), LessTime);
Also, you can overload the comparator on ordered containers such as set: 同样,您可以在比较器上重载比较器,例如set:
std::multiset<PhoneCall, LessTime> timeSet;
The use of an inline friend here, compared to a public static method is of minimal benefit. 与公共静态方法相比,在此使用内联朋友的好处很小。 The real benefit of inline friend is when doing operator overloads, such as
operator <<
内联朋友的真正好处是在执行运算符重载时,例如
operator <<
No, what you want is not possible. 不,您想要的是不可能的。 Instead,
std::sort
provides two overloads. 相反,
std::sort
提供了两个重载。 One that uses operator<
by default and an overload which takes a functor for the comparison: 默认情况下,它使用
operator<
和一个重载,该重载使用函子进行比较:
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
This can be used as such: 可以这样使用:
std::vector<PhoneCall> calls;
std::sort(calls.begin(), calls.end(), [](const PhoneCall& lhs, const PhoneCall& rhs) {
return lhs.hours < rhs.hours;
});
Notice the lambda function as the third parameter does compare by hours. 请注意lambda函数,因为第三个参数确实按小时进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.