简体   繁体   中英

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!

Comparator cannot be a method of class (method of class needs an object for which it is called). You can define compareNames as static function in CStreamSetup class:

class CStreamSetup {
  static bool CStreamSetup::compareNames(const QString &s1, const QString &s2);
  // ^^^
}; 

the definition of compareNames remains the same.

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

or you can just define comparator as free function:

bool compareNames(const QString &s1, const QString &s2)
{
    QString temp1 = s1.section("Stream", 1);
    //...
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM