开发者

C++ struct sorting error

开发者 https://www.devze.com 2022-12-28 23:12 出处:网络
I am trying to sort a vector of custom struct in C++ struct Book{ public:int H,W,V,i; }; with a si开发者_如何学Gomple functor

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

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

with a si开发者_如何学Gomple 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消