Home > Net >  c std::set compare function when object is member of the set
c std::set compare function when object is member of the set

Time:10-27

I have a set composed of objects; in order to work the operator< must be defined for ordering the objects inside the set. If I define the operator< as a friend function, it works; if I define the operator< as a member function I get the error:

Error C2678 binary '<': no operator found which takes a left-hand >operand of type 'const _Ty' (or there is no acceptable conversion).

I do not understand why the version of operator< implemented as member function does not work/what should be changed about it. I provide bellow a simplified example of the problem case:

class TestObj
{
private: 
    int m_a;
public:
    TestObj(int a): m_a{a} {}
    /* operator < as friend function works */
    /*friend bool operator< (const TestObj& t1, const TestObj& t2)
    {
        return t1.m_a < t2.m_a;
    }*/
    /* operator < as member function does not work! */
    bool operator< (const TestObj& t2)
    {
        return m_a < t2.m_a;
    }
};
void testSetCompare()
{
    std::set<TestObj> set1;
    set1.insert(10);
    set1.insert(20);
}

I do not understand why the version of operator< implemented as member function does not work/what should be changed about it.

CodePudding user response:

You need to make the member function const. Because you declared it as 'non-const' the compiler cannot decide if yout operator willl change *this so your operator cannot be used in a when you have a const TEstObj& what is needed for insert

bool operator< (const TestObj& t2) const
{
    return m_a < t2.m_a;
}

will do the job.

Edit: The "No acceptable converson" means that it cannot convert from const TestObj& to TestObj& because it would break the rules of const. (and your operator needs a TestObj&)

  • Related