Sign in to follow this  
Headkaze

Sorting array of structs by string

Recommended Posts

Headkaze    607
I have a struct defined as

[code]struct GameInfo
{
GameType Type;
const char *Name;
int StartScoreMode;
int EndScoreMode;
const char *ScoreModeName[4];
};[/code]

Using this I have

[code]GameInfo g_gameInfo[] =
{
// Type Name Start Score Mode End Score Mode Score Mode Name
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
{ GAMETYPE_KLONDIKE, "Klondike", SCOREMODE_KLONDIKE_STANDARD, SCOREMODE_KLONDIKE_VEGAS_CUMULATIVE, { "Standard", "Vegas", "Vegas (Cumulative)" } },
...
};[/code]

Now I have a need to access a sorted list of these by Name. So I created a Sort function

[code]struct SortGame
{
bool operator()(GameInfo* a, GameInfo* b) { (strcmp(a->Name, b->Name) < 0); }
};[/code]

Now I create a vector of pointers to have a sorted list of games

[code]for(int i=0; i<GAMETYPE_COUNT; i++)
g_gameInfoArray.push_back(&g_gameInfo[i]);

std::sort(g_gameInfoArray.begin(), g_gameInfoArray.end(), SortGame());

for(int i=0; i<GAMETYPE_COUNT; i++)
g_gameNameArray.push_back(g_gameInfoArray[i]->Name);[/code]

The problem is it's not sorting the games right. When I print out the name's in g_gameNameArray it lists them as

Brisbane
Maria
Streets
Indian
Rank & File
Number 10
Accordion
...

What is going wrong here?

Share this post


Link to post
Share on other sites
smasherprog    568
your sort function should return a Boolean value. Currently, it doesn't return anything. You should be receiving compiler errors on this, I don't even think it should compile as is.

Should be
struct SortGame
{
bool operator()(GameInfo* a, GameInfo* b) { return strcmp(a->Name, b->Name) < 0; }
};

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this