PDA

View Full Version : sort



av2306
20th February 2014, 14:24
HI,

I have data(int, string). for ex: {(23,"z"),(23,"c"),(100,"ex"),(1,"zz"),(2,"345")}

I want to sort combination of two keys.

output: {(1,"zz"),(2,"345"),(23,"c"),(23,"z"),(100,"ex")}

What is the right data structure to store two values and sort on two keys?

Thanks.

anda_skoa
20th February 2014, 17:20
Easiest way is to put the values in to instances of a class or struct and have that class implement a "less than" operator



struct Data
{
int i;
QString s;

bool operator<(const Data& other) const
{
// return true if "this" is less than "other", otherwise return false;
}
};


The put into a QList or QVector and use qSort()

Cheers,
_

d_stranz
22nd February 2014, 17:22
Or try the completely heretical concept using the C++ standard library std:: pair< int, QString > instead of defining a new class. std:: pair<> already has the comparison operators defined by default (http://www.cplusplus.com/reference/utility/pair/operators/) (and will sort the pairs exactly the way you asked).

ChrisW67
22nd February 2014, 23:57
Or (if heresy is not your thing ;) you could use QPair the same way.

av2306
23rd February 2014, 05:09
Thank you all. Let me try. :-)