PDA

View Full Version : Sorting a qLinkedList



pwaldron
16th January 2010, 13:32
Is it possible to sort a qLinkedList structure? The qLinkedList doesn't seem to have random access iterators, so the compiler complains when I try and pass the linked list to the sorting function. Simple code is shown below; if the qLinkedList is changed to qList then everything is fine, but my application needs iterators to remain valid after sorting, so qList/qVector aren't suitable.



#include <QtCore/QCoreApplication>
#include <QLinkedList>
#include <QtAlgorithms>

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

QLinkedList<int> list;
list << 5 << 2 << 7 << 12;
qSort (list.begin, list.end());

return a.exec();
}


Any ideas?

EDIT: It looks like the problem may be a relatively recent one. In Qt 4.1 qSort only required bidirectional iterators, which qLinkedList would support. In Qt 4.6 the requirement has been bumped up to random access iterators.

wysota
17th January 2010, 09:33
Did you try using std::sort()?

pwaldron
19th January 2010, 20:42
Same problem. std::sort requires a random access iterator, not a bidirectional one.

wysota
19th January 2010, 21:59
Both std::sort and qSort implement QuickSort and this one indeed needs a random access iterator. You can try doing bubble sort or insert sort, this should work on iterators with more restrictions.