Jump to content
  • Advertisement
Sign in to follow this  
Headkaze

Sorting array of structs by string

This topic is 2676 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

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


Using this I have

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)" } },
...
};


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

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


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

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

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

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


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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!