Search code examples
c++structoperator-overloadingsortcomparefunction

Operator overload for struct


I am not able to get this code work. I have read similar questions on the topic but I couldn't find a solution. error: no match for 'operator<' (operand types are 'car' and 'const int') { return *__it < __val; } That was the only meaningful hint in a lengthy error message.

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 }

Even creating a compare function with two arguements didn't work. Any helpwill be appreciated. Thanks.


Solution

  • Your question is lacking the actual question, but two things are obvious:

    1) You're violating strict weak ordering - if a < b then b < a cannot be true. Your comparison function breaks this. In fact, you're implementing operator< in terms of operator<=, which should be a red flag.

    2) your code could use a little formatting. Use clang-format or formatting function of your IDE for this (or a web interface for clang-format: link).