I have a 2D array like below. ( array[5][2] )
20 11
10 20
39 14
29 15
22 23
after sorting it should be like below.
10 20
20 11
22 23
29 15
39 14
that means the array should be sorted comparing the first column values only.
In Java there is a built in function capability to do that. like below.
Arrays.sort(a, new Comparator<Long[]>() {
@Override
public int compare(Long[] o1, Long[] o2) {
Long t1 = o1[1];
Long p1 = o1[0];
Long t2 = o2[1];
Long p2 = o2[0];
if (t1 == t2) {
return (p1 > p2 ? 1 : (p1 == p2 ? 0 : -1));
} else {
return (t1 < t2 ? -1 : 1);
}
}
});
So is there any C++ built in function capability to do these kind of stuff or how can i do this in C++ (the fastest implementation) ?
Thanks in advance :)
std::qsort()may be an easier built-in to wedge-fit into a classic 2D array when sorting by single column.std::sortaccepts a comparator as the third argument. Anyopsuch thatop(a,b)meansa < bis fine – function, lambda, functor object. Due to inlining, it’s usually faster thanqsortwith the same function, too.