PDA

View Full Version : sort multi in class



woraprud
21st January 2013, 16:11
Hi everyone,
I have question about sort data in class. i need sort value X and Y


class PointMatch {
public :
int X;
int Y;
QString Name;
};


In list have data before sort :
[2,5,'A']
[1,2,'B']
[1,3,'C']
[2,3,'D']
[1,1,'E']

I need after sort X and Y.

[1,1,'E']
[1,2,'B']
[1,3,'C']
[2,3,'D']
[2,5,'A']

If have sample code. help tell me.
Thank you.

Viper666
21st January 2013, 16:30
there is function which call qSort() (http://doc.qt.digia.com/qt/qtalgorithms.html)

Lesiok
21st January 2013, 16:35
PointMatch class must define operator <() and then you can use the qSort (http://qt-project.org/doc/qt-4.8/qtalgorithms.html#qSort) function

Santosh Reddy
21st January 2013, 16:42
Do you want to use Qt sort algorithms? if Yes then this is one way


#include <QList>
#include <QString>

#include <iostream>

class PointMatch
{
public :
PointMatch(int x, int y, const QString & name) : X(x), Y(y), Name(name) { }
PointMatch(const PointMatch & p) : X(p.X), Y(p.Y), Name(p.Name) { }

int X;
int Y;
QString Name;
};

bool PointMatchLessThan(const PointMatch & p1, const PointMatch & p2)
{
if(p1.X < p2.X)
return true;
else if(p1.X == p2.X)
{
if(p1.Y < p2.Y)
return true;
else
return false;
}
return false;
}

int main()
{
QList<PointMatch> points;

points.append(PointMatch(2, 5, "A"));
points.append(PointMatch(1, 2, "B"));
points.append(PointMatch(1, 3, "C"));
points.append(PointMatch(2, 3, "D"));
points.append(PointMatch(1, 1, "E"));

foreach(PointMatch point, points)
std::cout << "[" << point.X << ", " << point.Y << ", " << point.Name.toStdString() << "]" << std::endl;

qSort(points.begin(), points.end(), PointMatchLessThan);

std::cout << std::endl;

foreach(PointMatch point, points)
std::cout << "[" << point.X << ", " << point.Y << ", " << point.Name.toStdString() << "]" << std::endl;
}


other way is to implement a less than operator for the class

woraprud
22nd January 2013, 02:21
To. Santosh Reddy, Thank you very much. :D