Well, the short answer would be to not use std::qsort
at all, but std::sort
. But unfortunately the latter won't work, since unsigned int[3]
is not assignable. So here's the easiest std::qsort
solution.
First we define a custom comparator function:
// return -1 if a before b, 1 if after, 0 if equal
int compare(const void *a, const void *b)
{
const unsigned int *arg1 = reinterpret_cast<const unsigned int*>(a);
const unsigned int *arg2 = reinterpret_cast<const unsigned int*>(b);
if(arg1[2] > arg2[2])
return -1;
if(arg1[2] < arg2[2])
return 1;
return 0;
}
Which we then use to sort the array. Keep in mind that work
is an array of arrays, and thus work[0]
is an array of 3 unsigned int
s, there's no pointer indirection involved in any way. So it's perfectly suited for being sorted by std::qsort
:
std::qsort(work, sizeof(work)/sizeof(work[0]), sizeof(work[0]), compare);
By the way, the third element is indexed with 2
, since we usually start to count at 0
in C++ (and many other programming languages).
EDIT: Though, the best solution would indeed be to drop this array of arrays and use something more suited to C++, like a std::vector
of std::array<unsigned int,3>
s (or any other datastructure that fits a bit more to the actual context):
typedef std::array<unsigned int,3> uint3;
std::vector<uint3> work(N);
Which can then be sorted with a simple:
std::sort(std::begin(work), std::end(work),
[](const uint3 &a, const uint3 &b) { return a[2] > b[2]; });
Or, if you don't have C++11 (though in this case you won't have std::array
either and need to start thinking about a resonable datastructure apart from a mere 3-array):
struct compare
{
bool operator()(const uint3 &a, const uint3 &b) const
{
return a[2] > b[2];
}
};
std::sort(work.begin(), work.end(), compare());
As a bonus to much clearer code, you also most probably get a slight performance boost of std::sort
over std::qsort
.