I've got a set of pointers which I would like to iterate over in a deterministic manner. Obviously if I use the default sort order for set, this will be based on the pointers memory addresses which can be different each time the program runs. So I define a custom comparator which I want to use, but I don't want to change the templated type of the set (because it's used in a million places in the code), so I want to pass in a comparator object to the set constructor 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 have I forgotten to do?