【发布时间】:2018-07-30 10:10:16
【问题描述】:
考虑这段代码:
#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:在 '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:错误:“operator>”不匹配(操作数类型为“const MyStruct”和“const MyStruct”)
{ 返回 __x > __y; }
似乎是因为这里的这个函数没有const 限定符:
bool operator > (const MyStruct& other) {
return (key > other.key);
}
如果我添加它,
bool operator > (const MyStruct& other) const {
return (key > other.key);
}
然后一切又好了。为什么会这样?我对运算符重载不太熟悉,所以我只是把它放在内存中,我们需要添加const,但是为什么它在没有const 的情况下适用于operator< 仍然很奇怪。
【问题讨论】:
-
你用过哪个编译器?那是什么版本?
-
gcc 7.2.0 jdoodle.com/online-compiler-c++
-
@Rockstart5645 这里有什么相关性?
标签: c++ sorting operator-overloading