在C中对对象矢量进行排序

我有一个“信息”类,它将人的姓名和年龄存储在一个向量中.

所以…

class information {

private:
int age;
string name;

//etc,etc...
};

我如何按照年龄按升序/降序对矢量进行排序?

我相信你使用这样的东西.

sort(listofPeople.begin(),listofPeople.end(),greater<information>());

listofPeople将是矢量.

任何帮助将不胜感激.

解决方法

如果你想按年龄按非降序排序,一种方法是定义一个仿函数进行比较:
class Compareinformations {
    public:
    // after making Compareinformations a friend class to information...
    operator(const information& rhs,const information& lhs) {
        return rhs.age < lhs.age;
    }
};

然后做你的排序:

sort(listofPeople.begin(),Compareinformations());

你也可以重载operator<对于你的类,没有比较对象:

// inside your class
bool operator <(const information& rhs) {
    return age < rhs.age;
}

然后排序:

sort(listofPeople.begin(),listofPeople.end());

上面的示例假设您要按非降序(几乎递增但不完全)顺序排序.要执行非升序,只需更改<的所有出现次数.到>.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...