Search code examples
c++containersoperators

Why does std::set work with my free function operator<, but not my class member function operator<?


If I use the free function operator <, my program works. If I use the implementation inside the class, I get a compiler error. Why doesn't implementing this as a class member function work?

Part of the error I get:

usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_function.h:386:20: error: invalid operands to binary expression ('const my' and 'const my')
      { return __x < __y; }
               ~~~ ^ ~~~

The code :

class my{

    public:
        int a;
        double b;
        my(int p){
            a=p;
            b=0;
        }
        bool operator> (const my other){
            return this->a > other.a;
        }
        bool operator < (const my other) {
            return this->a < other.a;
        }
};

//  bool operator < ( const my othe2,const my other) {
//             return othe2.a < other.a;
//         }

int main(){

    set<my> s={10,5};
    s.emplace(8);
    s.emplace(-8);

    for(auto t:s){
        cout<<t.a<<",";
    }

}

Solution

  • They should be overloaded with const directive. Otherwise, the non const operators can't be applied to const my whatever a.k.a. std::set<my>::key_type whatever inside std::set. Add

    bool operator> (const my& other) const {
        return this->a > other.a;
    }
    bool operator < (const my& other) const {
        return this->a < other.a;
    }
    

    Additionally other should be passed by reference const my& other.