C ++结构排序错误 [英] C++ struct sorting error

查看:138
本文介绍了C ++结构排序错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中排序自定义结构的向量

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

有一个简单的函数

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

 
$ b

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

它给我例外无效运算符<



这个错误的含义是什么?



感谢

解决方案

sort 期望返回 bool 的函数,如果lhs在rhs之前, >

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

另请注意 const Book& code>参数,以避免复制。


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.

这篇关于C ++结构排序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆