gpt4 book ai didi

c++ - 非静态函数作为 C++ 中另一个函数的参数

转载 作者:行者123 更新时间:2023-11-30 00:37:52 25 4
gpt4 key购买 nike

我创建了一个类student,它的子类是comparatorcomparator 的构造函数采用一个名为 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!";
}
};

};

此外,我还创建了一个列表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.

那我该怎么办呢?如何以更好的方式调整排序?

最佳答案

我从你的评论开始:

I thought that I can write compare function for each case, but it seems even worse.

为什么更糟?我个人认为它运行速度更快(至少编译速度更快)并且更易于维护(功能更短)。

这样写是不是简单多了:

l.sort(student::compare_by_group);

而且这个实现更容易维护:

class student
{
...
static bool compare_by_name(const student& s1, const student& s2)
{
return s1.name < s2.name;
}
static bool compare_by_course(const student& s1, const student& s2)
{
return s1.course < s2.course;
}
static bool compare_by_group(const student& s1, const student& s2)
{
return s1.group < s2.group;
}

// Add the followings only if you really need this stuff
// e.g. to get comparator type from elsewhere
enum cmp_mode
{
NAME,
COURSE,
GROUP
};

static bool compare(cmp_mode, const student& s1, const student& s2)
{
switch(cmp_mode) {
case NAME: return compare_by_name(s1, s2);
...
}
}

};

关于c++ - 非静态函数作为 C++ 中另一个函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12659324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com