Quantcast
Channel: Why is const required for 'operator>' but not for 'operator
Viewing all articles
Browse latest Browse all 3

Why is const required for 'operator>' but not for 'operator

$
0
0

Consider this piece of code:

#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;    }}

It compiles fine and gives the output one would expect. But if I try to sort the structures in descending order:

#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;    }}

This gives me an error. 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; }

It seems to be because this function right here doesn't have a const qualifier:

bool operator > (const MyStruct& other) {        return (key > other.key);}

If I add it,

bool operator > (const MyStruct& other) const {        return (key > other.key);}

Then everything is fine again. Why is this so? I'm not too familiar with operator overloading, so I've just put it in memory that we need to add the const but it's still weird why it works for operator< without the const.


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images