根据某些成员变量对类对象的向量进行排序

问题描述:

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; });