Syed Iftekharuddin
Syed Iftekharuddin

Reputation: 146

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?

Upvotes: 1

Views: 1210

Answers (2)

Evan Teran
Evan Teran

Reputation: 90543

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

Upvotes: 5

Ishara Priyadarshana
Ishara Priyadarshana

Reputation: 88

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

Upvotes: 1

Related Questions