C++ - sort algorithm doesnt see my overloaded “<” operator for user-defined type.

前端 未结 2 676
情深已故
情深已故 2021-01-23 22:30

Ok so I have 1 user-defined type named fraction and it represents and ordinary fraction with a numerator and denominator. Here is the code:

class Fr         


        
相关标签:
2条回答
  • 2021-01-23 23:13
    bool operator<(Fraction& first,Fraction& second)
    

    The problem is that your overload of operator< only accepts non-const arguments, but the algorithm is trying to compare a constant reference to a Fraction with the elements in your container.

    Since operator< does not modify the contents of the compared objects, it should take them by const reference:

    bool operator<(Fraction const & first,Fraction const & second)
    
    0 讨论(0)
  • 2021-01-23 23:19

    Consider this code:

    Fraction a, b;
    bool res = (a < b);
    

    The second line is essentially a call to

    bool res = a.operator<(b);
    
    1. As suggested above - being const correct is going to serve you very well in a long run
    2. Define a member bool operator<(const Fraction&) const to make the sorting implementation happy or just go with the first suggestion above - be const-correct with bool operator<(const Fraction& a, const Fraction& b)
    0 讨论(0)
提交回复
热议问题