[英]no match for 'operator+' in sort in c++
I have defined a class 我已经定义了一个类
class Rent
{
public:
int s_time, duration, price, e_time;
Rent(int s, int d, int p)
{
s_time = s;
duration = d;
price = p;
e_time = s + d;
}
bool operator<(Rent const &r1)
{
return e_time < r1.e_time;
}
};
Wished to sort it on basis of e_time
, so I have defined <
over Rent
, however, I keep getting error 希望在e_time
基础上e_time
进行排序,所以我已经定义了<
over Rent
,但是,我一直在收到错误
rent.cpp:38:12: error: no match for ‘operator+’ (operand types are ‘std::vector<Rent>’ and ‘int’)
sort(R, R+n);
^
when I tried sort(R, R+n);
当我尝试sort(R, R+n);
. 。 R
is a vector of type Rent
and n
is integer(size of the vector). R
是Rent
类型的向量, n
是整数(向量的大小)。
Besides the above, I tried these two ways but still failed! 除了以上,我尝试了这两种方式,但仍然失败了!
sort(R, R + sizeof(R)/sizeof(R[0]));
sort(R.begin(), R.end());
I googled and got some solutions with lambdas but again the second parameter to sort() is of type int + custom_datatype. 我用Google搜索并获得了一些lambdas的解决方案,但sort()的第二个参数是int + custom_datatype类型。
Any help would be great. 任何帮助都会很棒。
sort(R, R+n);
sort(R, R + sizeof(R)/sizeof(R[0]));
will not work if R
is of type std::vector<Rent>
. 如果R
的类型是std::vector<Rent>
则不起作用。 There are two problems with those lines: 这些行有两个问题:
operator+()
is not defined for std::vector
. 没有为std::vector
定义operator+()
。 operator<()
function to be a const
member function. 编译器期望operator<()
函数是const
成员函数。 You can fix the operator<()
function by making it a const
member function. 您可以通过使其成为const
成员函数来修复operator<()
函数。
bool operator<(Rent const &r1) const
// ^^^^^
{
return e_time < r1.e_time;
}
That still does not resolve the first problem. 这仍然无法解决第一个问题。
However you should be able to use: 但是你应该可以使用:
sort(R.begin(), R.end());
after that. 之后。
In theory, you shouldn't have to make the operator<()
function a non- const
member function. 理论上,您不必将operator<()
函数作为非const
成员函数。 Take a look at http://en.cppreference.com/w/cpp/algorithm/sort . 请查看http://en.cppreference.com/w/cpp/algorithm/sort 。 See the description of the comp
argument. 请参阅comp
参数的说明。 It says: 它说:
The signature of the comparison function should be equivalent to the following: 比较函数的签名应等效于以下内容:
bool cmp(const Type1 &a, const Type2 &b);
The signature does not need to have
const &
, but the function object must not modify the objects passed to it. 签名不需要具有const &
,但是函数对象不能修改传递给它的对象。
However, not all compilers adhere to that. 但是,并非所有编译器都坚持这一点。 They expect the signature of the function to be such that they can work with const
objects. 他们希望函数的签名能够与const
对象一起使用。
According to error, R
is a std::vector<Rent>
but following code: 根据错误, R
是一个std::vector<Rent>
但是代码如下:
sort(R, R+n);
would work only for C style array. 只适用于C风格的数组。 If you want generic code that works for both C array and std::vector
write it as: 如果你想要适用于C数组和std::vector
通用代码,请将其写为:
std::sort( std::begin(R), std::end(R) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.