Re: Creating objects with functions.
Perhaps more to the point on sort vs qsort, the two can be called essentially identically except that sort doesn't require the comparator arguments to be void*, and is thus more type-safe:
Code:
#include <algorithm>
FooBar array[100];
//...
bool compareLess(const FooBar &a, const FooBar &b)
{
// or whatever
return a.val < b.val;
}
//...
int main()
{
//... Assume that array has been populated
//...
std::sort(array, array + 100, compareLess);
}
Code:
#include <stdlib.h>
int array[100];
//...
int compare (const void * a, const void * b)
{
FooBar *aF = (FooBar*)a;
FooBar *bF = (FooBar*)b;
if (aF.val < bF.val)
return -1;
if (aF.val > bF.val)
return 1;
return 0;
}
int main ()
{
//... Assume that array has been populated
//...
qsort (array, 100, sizeof(FooBar), compare);
}
Of course, std::sort does not require a comparator to be specified if the particular type has operator< defined anyway.