Custom comparator using explicit constructor to sort std :: set

I have a set of pointers that I would like to handle in a deterministic way. Obviously, if I use the default sort order for set, this will be based on the memory addresses of the pointers, which may be different each time the program starts. Therefore, I define a custom comparator that I want to use, but I do not want to change the template type of the set (because it was used in millions of places in the code), so I want to pass the comparator object to set, which is derived from std :: less

class TestClass
{
public:
    TestClass(int id_) : id(id_)    {}
    ~TestClass()                    {}
    int  getId() const              { return id;}
    void setId(int id_)             { id = id_; }
private: 
    int id; 
};

struct TestClassLessThan : public std::less<TestClass*>
{   // functor for operator<
    bool operator()(const TestClass* &_Left, const TestClass* &_Right) const
    {   // apply operator< to operands
        return (_Left->getId() < _Right->getId());
    }
};


int main(void)
{
    TestClassLessThan comp; 
    set<TestClass*> testSet(comp), testSet2(comp);

    TestClass* obj1 = new TestClass(1);
    TestClass* obj2 = new TestClass(2);
    testSet.insert(obj1);
    testSet.insert(obj2);

    TestClass* obj = *(testSet.begin());

    cout << "First run" << endl;
    BOOST_FOREACH(TestClass* o, testSet)  // expecting 1,2 - get 1,2
        cout << o->getId() << endl;

    // now change the ordering (based on id) and insert into a new set in the same order
    obj1->setId(3);
    testSet2.insert(obj1);
    testSet2.insert(obj2);

    cout << "Second run" << endl;
    BOOST_FOREACH(TestClass* o, testSet2) // expecting 2,3 - get 3,2
        cout << o->getId() << endl;

    delete obj1;
    delete obj2;
}

So my question is: what did I forget to do?

+2
source share
3 answers

. - std:: less, :

namespace std
{
    template<>
    struct less< TestClass*>
    {   // functor for operator<
    public:
        bool operator()(  TestClass* const  &_Left,  TestClass* const  &_Right) const
        {   // apply operator< to operands      
            return (_Left->getId() < _Right->getId());
        }
    };
}

, std:: set.

, , , " ", std:: less .

+3

std::set - Compare const&, Compare - .

, ( ), Compare, std::less.

std::less , std::less::operator(), , operator() TestClassLessThan.

, , " ".

, , , .

, Compare .

, , , , ( ).

hth.,

+3

. operator() std:: less .

, .

set<TestClass*, TestClassLessThan> testSet, testSet2;

, , const. ,

 // functor for operator<
    bool operator()(const TestClass* const&_Left, const TestClass* const&_Right) const
    {   
        cout << "comparing";
        // apply operator< to operands
        return (_Left->getId() < _Right->getId());
    }
+1

All Articles