简体   繁体   中英

Why won't qSort() work?

Ok, I'm trying to sort a list of my own TvShow classes to display a list of TvShows in the order decided by the user. This is what I've come up with thus far, after reading the documentation on qSort().

bool MainWindow::compareShowsByName(TvShow* showA, TvShow* showB)
{
    return showA->getShowName() < showB->getShowName();
}

QList<TvShow*> MainWindow::orderShowsByName()
{
    QList<TvShow*> orderedShowList = appSettings.TvShows;
    qSort(orderedShowList.begin(), orderedShowList.end(), compareShowsByName);
    return orderedShowList;
}

Of course, this fails with following errors:

../EpisodeNext/mainwindow.cpp: In member function 'QList<TvShow*> MainWindow::orderShowsByName()':
../EpisodeNext/mainwindow.cpp:192: error: no matching function for call to 'qSort(QList<TvShow*>::iterator, QList<TvShow*>::iterator, <unresolved overloaded function type>)'
../../QtSDK/Simulator/Qt/gcc/include/QtCore/qalgorithms.h:184: note: candidates are: void qSort(RandomAccessIterator, RandomAccessIterator, LessThan) [with RandomAccessIterator = QList<TvShow*>::iterator, LessThan = bool (MainWindow::*)(TvShow*, TvShow*)]
../EpisodeNext/mainwindow.cpp: In member function 'QList<TvShow*> MainWindow::orderShowsByAirDate()':
../EpisodeNext/mainwindow.cpp:199: error: no matching function for call to 'qSort(QList<TvShow*>::iterator, QList<TvShow*>::iterator, <unresolved overloaded function type>)'
../../QtSDK/Simulator/Qt/gcc/include/QtCore/qalgorithms.h:184: note: candidates are: void qSort(RandomAccessIterator, RandomAccessIterator, LessThan) [with RandomAccessIterator = QList<TvShow*>::iterator, LessThan = bool (MainWindow::*)(TvShow*, TvShow*)]
make: *** [mainwindow.o] Error 1

Any idea what can be wrong? I'm using the latest version of the Qt SDK (Qt SDK 1.1 RC with Qt 4.7.3)

Thanks in advance!

Robin, you did everything right except you need to declare your "compareShowsByName" function as global within your MainWindow.cpp file. So the code like this compiles and works fine:

bool compareShowsByName(TvShow* showA, TvShow* showB)
{
    return showA->getShowName() < showB->getShowName();
}

QList<TvShow*> MainWindow::orderShowsByName()
{
    QList<TvShow*> orderedShowList = appSettings.TvShows;
    qSort(orderedShowList.begin(), orderedShowList.end(), compareShowsByName);
    return orderedShowList;
}

Note: you don't necessarily need to declare "compareShowsByName" in your MainWindow.h unless you want to use it somewhere outside MainWindow (in any other part of your app). But if you still want to declare your "compareShowsByName" as a member function of your MainWindow class, just pass a pointer to a member-function correctly.

Hope that helps.

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