Search code examples
c++qtsortingqt5qsort

qSort() doesn't work with own compare function


I want to use qSort() as follows.

I have a compare function called

bool CStreamSetup::compareNames(const QString &s1, const QString &s2)
{
    QString temp1 = s1.section("Stream", 1);
    temp1 = temp1.section('_', 0, 0);

    QString temp2 = s2.section("Stream", 1);
    temp2 = temp2.section('_', 0, 0);

    return (temp1.toInt() < temp2.toInt());
}

and a QStringList with 160 elements called QStringList childKeys;

When I call the QSort function as follows:

qSort(childKeys.begin(), childKeys.end(), compareNames);

the following errors appear.

'compareNames': non-standard syntax; use '&' to create a pointer to member
'qSort': no matching overloaded function found
'void qSort(Container &)': expects 1 arguments - 3 provided
'void qSort(RandomAccessIterator, RandomAccessIterator)' expects 2 arguments - 3 provided

Thank you guys!


Solution

  • Static function

    The member function needs to be static if you want to use it as a comparator:

    static bool compareNames(const QString &s1, const QString &s2);
    

    Anonymous function (lambda)

    Another way (C++11 and later) is to use lambdas:

    qSort(childKeys.begin(), childKeys.end(), [this](const QString &s1, const QString &s2) {
        return compareNames(s1, s2);
    });
    

    STL function

    Side note: according to the docs, qSort is obsolete and Qt recommends using std::sort instead.