在C ++中排序对象的向量 [英] Sorting a vector of objects in C++
问题描述
说我有一个类信息,它存储的人的名称和年龄的向量。
所以...
类信息{
private:
int age;
string name;
// etc,etc ...
};
如何按照年龄升序/降序对向量进行排序?
我相信你使用这样的东西。
sort(listOfPeople.begin ,listOfPeople.end(),greater< Information>());
listOfPeople将是向量。
任何帮助将非常感激。
如果你想按照不降序按年龄排序,一种方法它是定义一个函子进行比较:
class CompareInformations {
public:
// CompareInformations一个朋友类到Information ...
operator(const Information& rhs,const Information& lhs){
return rhs.age< lhs.age;
}
};
然后按照你的排序:
sort(listOfPeople.begin(),listOfPeople.end(),CompareInformations());
您也可以重载 operator<
类,并且没有比较对象:
//在类中
bool operator<(const Information& rhs){
return age< rhs.age;
}
然后排序:
sort(listOfPeople.begin(),listOfPeople.end());上述示例假设您希望以非降序进行排序(几乎是 )。 升序,但不完全)。要执行非上升订单,只需将所有出现的<
更改为>
。
say I have a class "Information" and it stores the Name and Age of people in a vector.
so...
class Information {
private:
int age;
string name;
//etc, etc...
};
How would I sort the vector in either ascending/descending order with respect to age?
I believe you use something like this.
sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());
listOfPeople would be the vector.
Any help would be greatly appreciated.
解决方案 If you want to sort them in non-descending order by age, one way to do it is to define a functor for comparison:
class CompareInformations {
public:
// after making CompareInformations a friend class to Information...
operator(const Information& rhs, const Information& lhs) {
return rhs.age < lhs.age;
}
};
And then do your sort:
sort(listOfPeople.begin(), listOfPeople.end(), CompareInformations());
You could also overload operator<
for your class, and do without the comparison object:
// inside your class
bool operator <(const Information& rhs) {
return age < rhs.age;
}
Then sort it:
sort(listOfPeople.begin(), listOfPeople.end());
The above examples assume you want to sort in non-descending (almost ascending, but not quite) order. To do non-ascending order, just change all occurrences of <
to >
.
这篇关于在C ++中排序对象的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!