C++ struct sorting error

六眼飞鱼酱① 提交于 2019-12-12 16:14:02

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/2727890/c-struct-sorting-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!