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*>
{
bool operator()(const TestClass* &_Left, const TestClass* &_Right) const
{
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)
cout << o->getId() << endl;
obj1->setId(3);
testSet2.insert(obj1);
testSet2.insert(obj2);
cout << "Second run" << endl;
BOOST_FOREACH(TestClass* o, testSet2)
cout << o->getId() << endl;
delete obj1;
delete obj2;
}
So my question is: what did I forget to do?
source
share