c++qtsortingqlist

Sorting QList based on class property in Qt using Cpp


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?


Solution

  • @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);
    });