struct student{
string name;
float cgpa;
student(string name, float cgpa){
this -> name = name;
this -> cgpa = cgpa;
}
};
struct comp{
bool operator () (const student& x, student y) {
if ( x.name == "Wang" )
return 1;
if ( y.name == "Wang" )
return 0;
return x.name < y.name;
}
};
set < student, comp > batch ;
batch.insert(student("Wang", 8.1));
batch.insert(student("Ming", 6.32));
batch.insert(student("Bruce", 8.82));
batch.insert(student("Pandora", 7.63));
for(student i : batch)
cout<< i.cgpa << '\t ';我不能理解如何在集合的上面的program.THe输出中进行比较,结果是8.1 8.82 6.32 7.63。我不理解集合中的元素是如何比较的,以给出这个output.Can,有人能详细说明一下吗?
发布于 2020-04-23 18:27:06
comp试图以特殊的方式将"Wang"视为少于其他字符串。
正如HolyBlackCat所指出的,比较器是错误的"Wang" < "Wang" == true,而它应该是false。
可以通过以下方式进行修复:
struct comp
{
bool operator () (const student& x, const student& y) {
if (y.name == "Wang")
return false;
if (x.name == "Wang")
return true;
return x.name < y.name;
}
};使用元组比较可以避免这样的错误,因此:
struct comp
{
bool operator () (const student& lhs, const student& rhs) const
{
const bool lhs_is_not_wang = lhs.name != "Wang";
const bool rhs_is_not_wang = rhs.name != "Wang";
return std::tie(lhs_is_not_wang, lhs.name)
< std::tie(rhs_is_not_wang, rhs.name);
}
};订单是这样的
student("Wang", 8.1) (先“Wang”,然后按name)student("Bruce", 8.82)student("Ming", 6.32)student("Pandora", 7.63)的字典序排列
https://stackoverflow.com/questions/61384676
复制相似问题