0

I use std::set<CTest> and I overloaded the operator <(const CTest&) ok it is working, but I am trying to do the same with pointers:

std::set<CTest*>
operator <( CTest* )

it is not working, when inserting objects to the set it is not even going through the operator (I tried with break point).

Below is the code with both operators:

class CTest
{
private:
    int      m_nID;

public:
    CTest() : m_nID(0) {}
    CTest(int n) : m_nID(n) {}

    bool operator <( const CTest& p ) const
    {   return m_nID < p.m_nID; }

    bool operator <( CTest* p ) const
    {   return m_nID < p->m_nID; }

    void  PrintID() const { cout << m_nID << endl; }
};

int main()
{
    CTest* pNode1  = new CTest(1);
    CTest* pNode2  = new CTest(2);
    CTest* pNode3  = new CTest(1);

    std::set<CTest> setNode;
    setNode.insert(*pNode1);
    setNode.insert(*pNode2);
    setNode.insert(*pNode3);

    for (std::set<CTest>::iterator iter = setNode.begin();
         iter != setNode.end(); iter++)
    {
        (*iter).PrintID();
    }
    // With object it is working, I have only two objects:
    // 1
    // 2

    std::set<CTest*> setNode2;
    setNode2.insert(pNode1);
    setNode2.insert(pNode2);
    setNode2.insert(pNode3);

    for (std::set<CTest*>::iterator iter = setNode2.begin();
         iter != setNode2.end(); iter++)
    {
        (*iter)->PrintID();
    }
    // With pointers it is not working, three objects with duplicate:
    // 1
    // 2
    // 1

    delete pNode1, pNode2, pNode3;
    return 0;
}

Can you help me to make it work with pointers? THX

  • I thought I just needed an operator (it works like that when I use a set of objects but not a set of pointers). – Calivernon Mar 29 '23 at 13:11
  • The operator <( const CTest& p ) compares objects "p" and * this and works correctly, whys does not the operator <( CTest* p ) compare the pointers: "p" and "this"? – Calivernon Mar 29 '23 at 13:17

0 Answers0