c++使用多个对象属性映射自定义比较器



假设我有一个学生的映射,ID作为键,Student对象作为值。下面是示例:

struct Student{
int id;
int score;
string name;
}
map<int, Student> students;

我想按以下顺序对地图进行排序:Sort the students based on their test score, the student with lower ID comes first if they got the same score

是否可以使用多个对象属性创建自定义比较器?我该怎么做呢?

我正在使用地图,因为我也需要随机访问,在这种情况下,是否有更好的方法代替使用map?

更新我已经用ID和分数作为属性的新对象Mapkey更改了键。然后通过比较这些属性对映射进行排序。

但问题是:从地图中获得学生值有点棘手,因为分数随着时间的推移而变化,我必须更新键。我想知道是否有更好更简单的解决办法。

这是我的实现:


struct Mapkey {
int id;
int score;
};
struct cmp {
bool operator()(const Mapkey &p1, const Mapkey &p2) const {
if (p1.score == p2.score) {
return p1.id < p2.id;
}
return p1.score > p2.score;
}
};
map<Mapkey, Student*, cmp> sectionMap;

如果我理解正确,那么您首先要根据Student对象的测试分数对其进行排序。如果他们有相同的分数,那么他们的ID将被用作辅助键。

我建议使用类。您可以使用比较操作符以下列方式实现您想要的效果:

bool operator< (const Student& left, const Student& right)
{
if (left.score == right.score)
return left.id < right.id;
else
return left.score < right.score;
}

你可以把你的对象放在arrayvector中,这真的取决于你。

编辑:Remy的替代方案:

bool operator< (const Student& left, const Student& right)
{
return std::tie(left.score, left.id) < std::tie(right.score, right.id);
}

Edit2:下面是使用结构向量的完整实现。如果这不是你想要的,那么我放弃。

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
struct Student
{
int id;
int score;
std::string name;
// Constructor
Student(int a, int b, std::string s) : id(a), score(b), name(s) {}
// Operator overloading
bool operator < (const Student& obj) const
{
if (score == obj.score)
return id < obj.id;
else
return score < obj.score;
}
// Printing
void print()
{
std::cout << "id: " << id << ", score: " << score << ", name: " << name << 'n';
}
};
int main()
{
std::vector<Student> students;
students.push_back(Student(1, 55, "A"));
students.push_back(Student(4, 78, "D"));
students.push_back(Student(3, 55, "C"));
students.push_back(Student(2, 55, "B"));
students.push_back(Student(5, 65, "E"));
std::sort(students.begin(), students.end(), std::less<Student>());
//std::sort(students.begin(), students.end()); // You can use this too
std::cout << "Sorted vector:" << 'n';
for (auto it = students.begin(); it != students.end(); ++it)
it->print();
std::cout << 'n';
return 0;
}

上面代码的输出:

Sorted vector:
id: 1, score: 55, name: A
id: 2, score: 55, name: B
id: 3, score: 55, name: C
id: 5, score: 65, name: E
id: 4, score: 78, name: D