View Full Version : sorting an array of doubles [solved]
Cremers
24th September 2018, 15:28
Hi,
I was asking about sorting doubles but i seem to have found the answer. Thanks.
//-------------------------------------------------------------------------------
void sortdoubles(double *d, int num)
{
QList<double> tmp;
for (int i = 0; i < num; i++)
tmp << d[i];
qSort(tmp);
for (int i = 0; i < num; i++)
d[i] = tmp.at(i);
}
d_stranz
24th September 2018, 17:54
qSort() is obsolete and should not be used in new code. Besides, you can do the same thing with one line of code from the Standard Template Library (STL):
std::sort( d, d + num );
Cremers
25th September 2018, 07:54
Thanks. But if i want to know the sorting order and need to sort a pair, what do i do with std::sort()?
I am using QPair for that now:
QList<QPair<double, int>> tmp;
for (int i = 0; i < num; i++)
tmp.append(qMakePair(p->x, p->n));
qSort(tmp);
for (int i = 0; i < num; i++)
{
p->x = tmp.at(i).first;
p->n = tmp.at(i).second;
}
Can I sort a structure like typedef struct { double x; int n; } mysortstruct; ?
tuli
25th September 2018, 09:24
Yes, you need to have a coparison operator for your struct or pass a lambda to the std::sort. See here: https://en.cppreference.com/w/cpp/algorithm/sort
d_stranz
25th September 2018, 18:01
Using lambdas is a more advanced technique than simply defining a comparison function. For example, using a comparison function:
// UNTESTED CODE
typedef struct
{
double a;
int b;
} MyStruct;
// Comparison function
bool myStructLess( const MyStruct & lhs, const MyStruct & rhs ) // "lhs" = "left-hand side"
{
if ( lhs.a < rhs.a )
return true;
else if ( lhs.a > rhs.a )
return false;
else
return lhs.b < rhs.b;
}
std::vector< MyStruct > myStructVector;
std::sort( myStructVector.begin(), myStructVector.end(), myStructLess() );
But if you understand lambdas or functors, then use whatever method works best for you.
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.