I need to use std::qsort()
to sort an arry of nd-Point. But I get an error:
no known conversion from 'function<int (const void *, const void )>' to '__compar_fn_t' (aka 'int ()(const void *, const void *)')`
How to solve it, or sort it by dir in another method?
#include <iostream>
#include <functional>
int d, n;
struct Point {
int *x;
Point() : x(new int[d]) {};
};
std::function<int(const void *, const void *)> make_cmp(int dir) {
return [dir](const void *a, const void *b)->int {
auto a_ = (Point *)a;
auto b_ = (Point *)b;
return a_->x[dir] - b_->x[dir];
};
}
void sort_points(Point *value, int length, int dir) {
std::qsort(value, length, sizeof(Point), make_cmp(dir));
}
CodePudding user response:
If you must use std::qsort
then you are basically writing in C, not C . This might be one of the few situations where a global variable is the least bad approach.
static thread_local int dir;
int cmp(const void *a, const void *b) {
auto a_ = (const Point *)a;
auto b_ = (const Point *)b;
return a_->x[dir] - b_->x[dir]; // beware of overflow
}
void sort_points(Point *value, int length, int d) {
dir = d;
std::qsort(value, length, sizeof(Point), cmp);
}
If this will never be called from more than one thread at a time, then you can drop the thread_local
.
(Note that if the values might exceed the range [INT_MIN/2, INT_MAX/2]
then you need to replace the subtraction with something that isn't vulnerable to overflow.)