Warm tip: This article is reproduced from serverfault.com, please click

Sorting a QString list by numbers C++

发布于 2020-11-29 15:37:46

I'm using Qt and I created a ranking scene which contains all the players list with their score, so I have a QList<QString> list, every QString contains a name and a score, separated by a space like this Mario 50. Now the problem is: how can I sort the list by the lowest score?

Questioner
UndefinedDuck
Viewed
0
Ngoc Minh Nguyen 2020-11-30 00:21:21

You can use std::sort() with a lambda like this

std::sort(str_list.begin(), str_list.end(), [](const QString &lhs, const QString &rhs)
{
    int num_lhs = lhs.split(' ').last().toInt();
    int num_rhs = rhs.split(' ').last().toInt();
    return num_lhs < num_rhs;
});