我正在研究一个问题的简单解决方案,我想对通过以下方法定义的对象矢量进行排序:
class Person {
public:
string name_;
double age_;
};
我正在尝试修改sort()的第三个参数,以便我可以按年龄对我的矢量进行排序,但是当两个年龄相同时,它会在该年龄内按字母顺序排序。
vector<Person> people;
//code to populate vector
sort(people.begin(), people.end(), sort_decision);
我不确定是否可以在我的sort_decision代码中添加决策结构,大致如下:
inline bool sort_decision(Person const& lhs, Person const& rhs) {
if (lhs.age_ == rhs.age_)
return lhs.age_ < rhs.age_ && lhs.name_ < rhs.name_;
else
return lhs.age_> rhs.age_;
}
谢谢你的帮助。
答案 0 :(得分:1)
排序决定应该是这样的
inline bool sort_decision(Person const& lhs, Person const& rhs) {
if (lhs.age_ == rhs.age_)
lhs.name_ < rhs.name_;
else
return lhs.age_> rhs.age_;
}
因为如果if (lhs.age_ == rhs.age_)
为真,return lhs.age_ < rhs.age_
将始终为false,并且如果年龄相同,您的比较器将返回false。