Linked by MOS6510 on Thu 10th Jan 2013 23:25 UTC
Thread beginning with comment 548481
To view parent comment, click here.
To read all comments associated with this story, please click here.
To view parent comment, click here.
To read all comments associated with this story, please click here.
Except in C, there is no way to sort anything without passing a compare function to qsort. Even an array of ints needs a hand-coded, if trivial, compare function passed to it.
Actually, the fact that qsort takes a comparator function means that it is much better than a simple sort() method on an array object. It allows you much more freedom in comparing compound and complex objects, not just primitive values. How, for instance, do you sort an array of structures/objects sensibly? The language doesn't know how, so you have to provide a comparator. This is one of the less problematic features of the standard C library - providing generic interfaces for everything. If you need your ultra-fast ultra-optimized sorter, you can always code it yourself.
In Java, your class extends Comparable, then provides a definition of comparesTo(). You can now use your class with anything that wants to sort or search. You could argue the difference is just semantics or syntactic sugar. Still, the concept and syntax of function pointers is considerably more difficult to understand, and results in code that isn't as checkable by the compiler and can cause really wacky things to happen if you mess it up. In C, if I accidentally pass my string compare function to qsort while I'm trying to sort an array of ints, the program will compile and run, and then screw up badly at runtime.





Member since:
2006-05-20
Except in C, there is no way to sort anything without passing a compare function to qsort. Even an array of ints needs a hand-coded, if trivial, compare function passed to it.