考虑这段代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
bool operator < (const MyStruct& other) {
return (key < other.key);
}
};
int main() {
std::vector < MyStruct > vec;
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));
vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
std::sort(vec.begin(), vec.end());
for (const MyStruct& a : vec) {
cout << a.key << ": " << a.stringValue << endl;
}
}
它编译得很好,并给出了预期的输出。但如果我尝试按降序对结构进行排序:
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
bool operator > (const MyStruct& other) {
return (key > other.key);
}
};
int main() {
std::vector < MyStruct > vec;
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));
vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
std::sort(vec.begin(), vec.end(), greater<MyStruct>());
for (const MyStruct& a : vec) {
cout << a.key << ": " << a.stringValue << endl;
}
}
这给了我一个错误。 Here is the full message :
/usr/include/c++/7.2.0/bits/stl_function.h: In instantiation of 'constexpr bool std::greater<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = MyStruct]':
/usr/include/c++/7.2.0/bits/stl_function.h:376:20: error: no match for 'operator>' (operand types are 'const MyStruct' and 'const MyStruct')
{ return __x > __y; }
好像是因为这里的这个函数没有const
限定词:
bool operator > (const MyStruct& other) {
return (key > other.key);
}
如果我添加它,
bool operator > (const MyStruct& other) const {
return (key > other.key);
}
然后一切又好了。为什么会这样?我对运算符重载不太熟悉,所以我只是把它放在内存中,我们需要添加 const
但是为什么它适用于 operator<
仍然很奇怪没有 const
.
最佳答案
你会得到不同的行为,因为你实际上是在调用两个不同的(重载)sort功能。
在第一种情况下,您调用两个参数 std::sort
, 它使用 operator<
直接地。由于 vector 元素的迭代器产生非常量引用,它可以应用 operator<
很好。
在第二种情况下,您使用的是 std::sort
的三参数版本.接受仿函数的那个。你通过std::greater
.那个仿函数有一个 operator()
声明如下:
constexpr bool operator()( const T& lhs, const T& rhs ) const;
注意 const 引用。它将需要比较的元素绑定(bind)到 const 引用。所以你自己的operator>
也必须是正确的。
如果您调用 std::sort
与 std::less
, 你的 operator<
会产生同样的错误,因为它不是 const 正确的。
关于c++ - 为什么 'operator>' 需要 const 而 'operator<' 不需要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48878629/