[Qt-interest] Using qSort with lists of QPointers
Frederico A. M. Prado
famprado at terra.com.br
Sun Sep 5 22:10:00 CEST 2010
Just implement the "<" operator in the class whose objects you want to
sort and in the implementation make sure you compare the value pointed by
your pointers and not the pointers themselves. You can do any comparison
you wish within the operator overload function.
Something like:
bool operator <(const MyClass& other) const {return
(this->comesBefore(other));}
On Sun, 05 Sep 2010 16:51:10 -0300, Ellen Kestrel <dragonflykes at gmail.com>
wrote:
> I'm trying to use qSort to sort a list of QPointers to a class (which
> subclasses QObject). There is a public lessThan function actually within
> the class itself, and when I was sorting the list by hand I simply
> called it
> from the class that manages the list. Since I want to use qSort in the
> list-managing class, I defined a member function in that class with only
> this line of code:
>
> bool ListManager::objPrecedes (QPointer<MyClass> c1, QPointer<MyClass>
> c2)
> {
> return c1->comesBefore (c2);
> }
>
> and tried calling qSort as
>
> qSort (list.begin (), list.end (), objPrecedes);
>
> but this gives me a compiler error:
>
> error: no matching function for call to ‘qSort(QList<QPointer<MyClass>
>> ::iterator, QList<QPointer<MyClass> >::iterator, <unresolved overloaded
> function type>)’
> /usr/include/qt4/QtCore/qalgorithms.h:184: note: candidates are: void
> qSort(RandomAccessIterator, RandomAccessIterator, LessThan) [with
> RandomAccessIterator = QList<QPointer<MyClass> >::iterator, LessThan =
> bool
> (ListManager::*)(QPointer<MyClass>, QPointer<MyClass>)]
>
> Can anyone tell me what I might be doing wrong, here? I thought about
> simply overloading the < operator and not passing the function as an
> argument, but my guess is that since this is a list of pointers, it will
> simply compare the values of the pointers rather than try to use < on the
> objects they point to.
>
> EK
More information about the Qt-interest-old
mailing list