2016-10-15 19 views
0

我有一個QList<QStringList>名爲其中sortme每個QStringList第一QString是作爲串中的有效的整數,例如:Qt的4.8:試圖QStringList中的第一元件上排序的QList <QStringList>作爲整數

exampleQStringList << "5" << "foo" << "bar"

對於qsort,這是4.8使用而不是std:,我知道我想要一個比較函數。這是我認爲我需要寫:

bool MainWindow::qslLessThan(const QList<QStringList> &v1, const QList<QStringList> &v2) 
{ 
    // here I would get the first element.toInt() and return < 
    return(true); 
} 

然後:

qSort(sortme.begin(), sortme.end(), qslLessThan); 

我失去了一些東西,很顯然,因爲編譯器抱怨「錯誤:調用「快速排序沒有匹配功能(的QList :: iterator,QList :: iterator,'''儘管我試圖對QList<QStringList>sortme進行排序。

回答

3

首先,qsort()所要求的函數必須是一個原始函數,而不是任何類的成員。其次,在你的情況下,這個比較函數必須採用QStringList引用而不是QList引用,因爲它是你正在比較的QStringLists。

#include <QCoreApplication> 
#include <QDebug> 

bool lessThan(const QStringList& v1, const QStringList& v2) 
{ 
    return v1.first() < v2.first(); 
} 

int main(int argc, char *argv[]) 
{ 
    QCoreApplication a(argc, argv); 

    QList<QStringList> sortme; 

    QStringList entryOne = QStringList() << "1" << "foo1" << "bar1"; 
    QStringList entryTwo = QStringList() << "2" << "foo2" << "bar2"; 
    QStringList entryThree = QStringList() << "3" << "foo3" << "bar3"; 

    sortme << entryTwo << entryOne << entryThree; 

    qSort(sortme.begin(), sortme.end(), lessThan); 

    // Print out the list data so we can see that it got sorted ok 
    for(int i = 0; i < sortme.size(); i++) 
    { 
     QString data = sortme.at(i).join(","); 
     qDebug() << QString("Item %1: %2").arg(i + 1).arg(data); 
    } 

    return a.exec(); 
} 
+0

啊,我太親近了 - 我以爲是qstringlist comparitor,但是由於錯誤信息而改變了它。靜態的東西就是我所缺少的東西,我將它從課堂中移出並放回到qstringlist中,並且它工作正常。 – fyngyrz