PDA

View Full Version : Sort dictionary



nico
29-05-2016, 10:17 AM
I have a dictionary with key SteamId and value score (int).

(I'd like to sort it in a way) to be able to get the top 3 players in descending order.

Can't think of a proper way to do that. Help appreciated.

Solokiller
29-05-2016, 10:37 AM
Dictionaries can't be sorted. You'll have to iterate over all its keys and sort the values.

This is one way to do it (untested):



class PlayerData
{
string szSteamID;
int iScore;

PlayerData( const string& in szSteamID, int iScore )
{
this.szSteamID = szSteamID;
this.iScore = iScore;
}

int opCmp( const PlayerData@& other ) const
{
//If scores are equal, returns 0
//If this has more, returns > 0.
//If this has less, returns < 0.
return iScore - other.iScore;
}
}

/**
* Gets the top uiNumPlayers players, using their score to sort them.
* @param pDict Dictonary of steam ID -> score
* @param uiNumPlayers Maximum number of players to get.
* @return Array of the top uiNumPlayers players, sorted by score.
*/
array<PlayerData@> GetTopNPlayers( dictionary@ pDict, const uint uiNumPlayers )
{
array<string>@ pKeys = pDict.getKeys();

array<PlayerData@> players;

//Convert dictionary to array.
for( size_t uiIndex = 0; uiIndex < pKeys.size(); ++uiIndex )
{
int iScore;

//Shouldn't return false, unless you inserted something other than an int.
if( pDict.get( pKeys[ uiIndex ], iScore ) )
{
players.insertLast( @PlayerData( pKeys[ uiIndex ], iScore ) );
}
}

//Sort it by score.
players.sortDesc();

//Remove players that weren't requested.
if( players.length() > uiNumPlayers )
{
players.resize( uiNumPlayers );
}

return @players;
}


This is a bit expensive due to the creation of PlayerData objects. If possible, try to have a class that you store the score in, then store that in the dictionary.

nico
30-05-2016, 09:50 AM
Many thanks!