PDA

View Full Version : why doesn't qSort work when a QList hosts a pointertype?



momesana
4th October 2009, 04:01
Hi, I have a QList of pointers and would like to sort them. But it doesn't work because QList seems to only operator on Object not on pointers. It probably boils down to the fact that qSort simply compares the two Types with the < operator and thus ends up comparing the pointer addresses in my case instead of the real value. Maybe I should pass a function to qSort where I compare the values of the types instead. Here is a simple example to demonstrate what I mean (works fine on stack objects but fails if the objects are created on the heap):



#include <QtGui>

class X
{
public:
X(int value) : m_value(value) { }
bool operator<(const X& x) const { return m_value < x; }
operator int() const { return m_value; }
private:
int m_value;
};

int main(int argc, char** argv)
{
QApplication app(argc, argv);

qDebug() << "----------- list of objects -------------";
QList<X> list1;
list1 << X(7) << X(18) << X(-5) << X(4);
qSort(list1.begin(), list1.end());
foreach(X x, list1)
qDebug() << x;

qDebug() << "------------ list of pointers --------------";
QList<X*> list2;
list2 << new X(1) << new X(3) << new X(0) << new X(6);
qSort(list2.begin(), list2.end());
foreach(X* x, list2)
qDebug() << *x;
}
Thanx in advance

momesana
4th October 2009, 04:28
Ok, providing a lessThan function that takes two Pointers as parameters solved it :-). Applied to the above example it would look like that:



#include <QtGui>

class X
{
public:
X(int value) : m_value(value) { }
bool operator<(const X& x) const { return m_value < x; }
operator int() const { return m_value; }
private:
int m_value;
};

bool lessThan(const X* x1, const X* x2) { return *x1 < *x2; }

int main(int argc, char** argv)
{
QApplication app(argc, argv);

qDebug() << "----------- list of objects -------------";
QList<X> list1;
list1 << X(7) << X(18) << X(-5) << X(4);
qSort(list1.begin(), list1.end());
foreach(X x, list1)
qDebug() << x;

qDebug() << "------------ list of pointers --------------";
QList<X*> list2;
list2 << new X(1) << new X(3) << new X(0) << new X(6);
qSort(list2.begin(), list2.end(), lessThan);
foreach(X* x, list2)
qDebug() << *x;
}