我student
用 subclass做了一个类comparator
。的构造函数comparator
接受一个名为的参数cmp_mode
,该参数指定我们应该如何比较学生。
class student
{
public:
std::string name;
int course, group;
student(std::string name,
int course,
int group): name(name)
{
this->course = course;
this->group = group;
}
enum cmp_mode
{
NAME,
COURSE,
GROUP
};
class comparator
{
cmp_mode mode;
public:
comparator(cmp_mode mode)
{
this->mode = mode;
}
bool compare(student s1, student s2)
{
if (mode == NAME)
return s1.name < s2.name;
else if (mode == COURSE)
return s1.course < s2.course;
else if (mode == GROUP)
return s1.group < s2.group;
else
throw "Oh god! We can't compare variables using these keys!";
}
};
};
另外,我创建了一个list
of students
,现在我想使用比较器子类对这个列表进行排序。
std::list<student> l;
student st1("Anya", 2, 5);
student st2("Misha", 4, 2);
student st3("Yasha", 1, 3);
l.push_back(st1);
l.push_back(st2);
l.push_back(st3);
student::comparator by_group(student::GROUP);
l.sort(by_group.compare);
但我收到以下错误。
ERROR: Reference to non-static member function must be called.
所以我该怎么做?如何以更好的方式调整排序?