简体   繁体   中英

C++ struct sorting error

I am trying to sort a vector of custom struct in C++

struct Book{
public:int H,W,V,i;
};

with a simple functor

class CompareHeight
{
public:
    int operator() (Book lhs,Book rhs)
    {
        return lhs.H-rhs.H; 
    }
};

when trying :

vector<Book> books(X);
.....
sort(books.begin(),books.end(), CompareHeight());

it gives me exception "invalid operator <"

What is the meaning of this error?

Thanks

sort expects a function that returns bool , which is true iff the lhs precedes the rhs:

bool operator() (const Book& lhs, const Book& rhs)
{
    return lhs.H < rhs.H; 
}

Also note the change to const Book& parameters, to avoid copying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM