I think you did everything right, almost.
Your problem is that you have a set of Game pointers but your operator compares Game objects. If you make it a set of objects instead that should work fine.
If for some reason you need or prefer a set of pointers here is one way I would do it:
Code:
#include <iostream>
#include <set>
struct Game
{
Game(int defaultGameNum) : gameNum(defaultGameNum) {}
int gameNum;
};
struct GamePtrLessThan
{
bool operator()(const Game* const lhs, const Game* const rhs) const
{
// If rhs is null, then either both are null, or
// only rhs, either way return false.
if (rhs == 0)
return false;
// Since rhs is not null but lhs is, return true.
if (lhs == 0)
return true;
// Neither are null, so check the gameNum.
return lhs->gameNum < rhs->gameNum;
}
};
int main()
{
Game* pGame1 = new Game(1);
Game* pGame2 = new Game(2);
Game* pGame3 = new Game(3);
Game* pGame4 = new Game(4);
Game* pGame5 = 0;
std::set<Game*, GamePtrLessThan> gameSet;
gameSet.insert(pGame3);
gameSet.insert(pGame1);
gameSet.insert(pGame4);
gameSet.insert(pGame5);
gameSet.insert(pGame2);
std::set<Game*, GamePtrLessThan>::const_iterator iterGamePtr = gameSet.begin();
std::set<Game*, GamePtrLessThan>::const_iterator iterEnd = gameSet.end();
for (; iterGamePtr != iterEnd; ++iterGamePtr)
{
Game* pCurrentGame = *iterGamePtr;
if (pCurrentGame)
std::cout << pCurrentGame->gameNum << std::endl;
else
std::cout << "Null pointer." << std::endl;
}
return 0;
}
EDIT: Emphasized important code.