std::max_element正在查找->操作员

std::max_element looking for -> operator

本文关键字:gt 操作员 查找 max element std      更新时间:2023-10-16

我试图找到存储在向量中的学生的最大分数。这是我的密码。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());