struct的运算符重载

时间:2016-10-03 13:51:20

标签: c++ struct operator-overloading sortcomparefunction

我无法使此代码正常工作。我已经阅读了有关该主题的类似问题,但我找不到解决方案。 错误:'operator<'不匹配(操作数类型是'car'和'const int')        {return * __ it< __val; } 这是冗长的错误消息中唯一有意义的暗示。

struct car{
string name;
int l,h;
int operator<(/*const car& a,*/const car& b){
    return (this->l)<=(b.l);
};
int main(){int t;
cin>>t;
while(t--){
int n;
cin>>n;
 vector<struct car> a(n);
int i=0;
while(i<n){
    ws(cin);cin>>a[i].name>>a[i].l>>a[i++].h;
}
sort(a.begin(),a.end());
//more code }

即使使用两个参数创建比较函数也不起作用。 任何帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:0)

你的问题缺乏实际问题,但有两件事是显而易见的:

1)您违反了严格的弱排序 - 如果a < bb < a不能成立。你的比较函数打破了这个。事实上,您在operator<方面正在实施operator<=,这应该是一个红旗。

2)您的代码可以使用一点格式。为此使用IDE的clang格式或格式化功能(或clang格式的网络界面:link)。