Thanks for a solution in C, now I would like to achieve this in C++ using std::sort and vector:
typedef struct { double x; double y; double alfa; } pkt;
vector< pkt > wektor; filled up using push_back(); compare function:
int porownaj(const void *p_a, const void *p_b) { pkt *pkt_a = (pkt *) p_a; pkt *pkt_b = (pkt *) p_b; if (pkt_a->alfa > pkt_b->alfa) return 1; if (pkt_a->alfa < pkt_b->alfa) return -1; if (pkt_a->x > pkt_b->x) return 1; if (pkt_a->x < pkt_b->x) return -1; return 0; } sort(wektor.begin(), wektor.end(), porownaj); // this makes loads of errors on compile time
What is to correct? How to use properly std::sort in that case?
std::sorttakes a different compare function from that used inqsort. Instead of returning –1, 0 or 1, this function is expected to return aboolvalue indicating whether the first element is less than the second.You have two possibilites: implement
operator <for your objects; in that case, the defaultsortinvocation without a third argument will work; or you can rewrite your above function to accomplish the same thing.Notice that you have to use strong typing in the arguments.
Additionally, it’s good not to use a function here at all. Instead, use a function object. These benefit from inlining.