std::max_element正在查找->操作员
std::max_element looking for -> operator
我试图找到存储在向量中的学生的最大分数。这是我的密码。SL是学生对象的向量。
class Student{
public:
int returnScore(){return score;}
private:
int score;
};
class StudentList{
public:
vector<Student>sl;
bool compare( Student& s1,Student &s2)
{
return (s1.returnScore()<s2.returnScore());
}
void highest_score()
{
auto max_score = max_element(sl.begin(),sl.end(),compare);
if(max_score == sl.end()){}
//cout<<"Container empty.n";
else{}
// cout<<*max_score;
}
};
int main()
{
StudentList l;
l.highest_score();
}
编译器把我带到C++官方库,并给出了错误。
error: must use '.*' or '->*' to call pointer-to-member function in '((__gnu_cxx::__ops::_Iter_comp_iter<bool (StudentList::*)(Student&, Student&)>*)this)->__gnu_cxx::__ops::_Iter_comp_iter<bool (StudentList::*)(Student&, Student&)>::_M_comp (...)', e.g. '(... ->* ((__gnu_cxx::__ops::_Iter_comp_iter<bool (StudentList::*)(Student&, Student&)>*)this)->__gnu_cxx::__ops::_Iter_comp_iter<bool (StudentList::*)(Student&, Student&)>::_M_comp) (...)'|
我的编译器告诉我compare
需要是一个静态函数,而不是一个常规成员函数:
static bool compare( Student& s1,Student &s2)
然后一切都编译得很好。
auto max_score = max_element(sl.begin(),sl.end(),compare);
您不能这样做,因为compare
是一个方法,而max_element
没有此方法所属的对象。换句话说,您不能只调用compare
,因为您还需要调用它的对象。
你可以把比较变成一种静态方法:
static bool compare( Student& s1,Student &s2)
{
return (s1.returnScore()<s2.returnScore());
}
这会奏效的。
或者,您可以结束通话进行比较:
auto max_score = max_element(sl.begin(),sl.end(),[this](Student& s1,Student& s2) {return compare(s1,s2);});
但对我来说,这似乎是很多代码,而不是将compare变成函数/静态方法。
如其他答案中所述,使类成员函数static
即可完成此任务。另一种选择是像一样在Student类中定义operator<
inline bool operator<(const Student& s2)
{
return (this->returnScore()<s2.returnScore());
}
并调用std::max_element(使用默认运算符<(作为
auto max_score = max_element(sl.begin(),sl.end());
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C++ 与操作员不匹配<<
- 操作员C++的模棱两可的过载
- C++中>>操作员过载时出现问题?
- NaN 上的宇宙飞船操作员
- 比根<操作员
- SFINAE不能防止模棱两可的操作员过载吗?
- 什么是现实中的"endl"(或任何输出操纵器)?它是如何实现的,它如何与操作员<<一起工
- 为什么"delete"操作员给我访问权限冲突
- 为什么使操作员成为新的专用会打破 std::shared_ptr?
- 在这种情况下是私有的吗?试图使操作员<<过载
- C++操作员过载>>
- 是否有 C++20 浮点数的包装器,使我能够默认宇宙飞船操作员?
- 与异常处理程序中的操作员<<不匹配
- 复印作业操作员说明
- 友谊和操作员+=重载
- >操作员在比较两个C++容器时会怎么做?
- 与操作员比较两个计时时间点
- C 操作员&gt;&gt;与突变器过载