• Advertisement
Sign in to follow this  

Sorting array of structs by string

This topic is 2344 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
Sign in to follow this  

  • Advertisement