C++结构排序错误

发布于 2024-08-30 12:58:47 字数 427 浏览 12 评论 0原文

我尝试

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

使用简单函子

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

在尝试时

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

对 C++ 中的自定义结构向量进行排序:它给了我异常“无效运算符 <”

这个错误是什么意思?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

厌味 2024-09-06 12:58:47

sort 需要一个返回 bool 的函数,当且仅当左侧在右侧之前时,该函数为 true:

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

另请注意对 const Book& 参数的更改,以避免复制。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文