根据某些成员变量对类对象的向量进行排序 [英] Sort vector of class objects based on some member variable

查看:56
本文介绍了根据某些成员变量对类对象的向量进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Record {

    public:
       Record();

    private:
       string id;
       double score;
};

我们在某个地方定义了Record对象的向量,即

Somewhere we define a vector of Record objects, i.e.,

vector<Record> records(N);
// Initialize records somehow

我想基于 score (以降序排列)对记录进行排序,并跟踪 Record 的其他成员变量(在这种情况下,仅是 score,但一般而言).

I would like to sort records based on score (in descending order) keeping track of the other member variables of Record (in this case just the score, but in general whatever else).

推荐答案

您可以实现比较运算符.

You can implement the comparison operators.

bool Record::operator<(const Record& rhs) {
  return score < rhs.score;
}

bool Record::operator<=(const Record& rhs) {
  return score <= rhs.score;
}

请注意,如果您定义< < = ,则还应该定义其他比较运算符> > = == != .您还应该强制执行严格的弱排序(例如, a< b b< c 意味着 a< c ).

Note, if you define < and <=, you should also probably define the other comparison operators >, >=, ==, and !=. You should also enforce a strict weak ordering (e.g. a < b, b < c implies a < c).

然后按降序排序,您可以使用以下内容...

Then to sort descending, you could use the following...

std::sort(records.begin(), records.end(), 
  [] (const Record& lhs, const Record& rhs) -> bool { return lhs > rhs; });

这篇关于根据某些成员变量对类对象的向量进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆