Sorting QList based on class property in Qt using Cpp

980 Views Asked by At

I have a QList qList, I want to sort this based on the property "playerRank" in Players class. The Players class is as shown below.

class Players
{
public:
    Players();
    int playerId;
    QString playerName;
    int playerRank;

    void setPlayerId(int id);
    void setPlayerName(QString name);
    void setPlayerRank(int rank);
};


#include "players.h"

Players::Players()
{

}

void Players::setPlayerId(int id)
{
    playerId = id;
}

void Players::setPlayerName(QString name)
{
    playerName = name;
}

void Players::setPlayerRank(int rank)
{
    playerRank = rank;
}

How can I do this?

2

There are 2 best solutions below

0
Evan Teran On BEST ANSWER

@Ishra's answer is technically correct, but we can do better.

  1. It's usually better to use the standard algorithms whenever possible
  2. Make the parameters const so it works with containers to const objects too
  3. No need for an inefficient "capture everything by copy" in the lambda
std::sort(qList.begin(), qList.end(), [](const Players& p1, const Players& p2) {  
    return (p1.playerRank < p2.playerRank);
});
0
Ishara Priyadarshana On

you can you qSort and pass a lambda as a comparator.

 qSort(qList.begin(), qList.end(), 
     [=] (Players& p1, Players& p2)->bool  
     {  
        return (p1.playerRank < p2.playerRank);  
     }
 );