Since I'm too lazy to learn how to sort with the STL, here is a simple way to sort arrays in C using a function pointer. (Source is at the bottom of the page.) It works with simple data types or even structs or objects. Here's the function prototype:
void sort(void* array, const int arrayLength, const int elementSize, int (*compareFunction)(void*, void*));
Not too bad. In fact, after I'd finished everything I found out there's already a sort routine in the c library with the exact same function definition. The only thing the user has to supply is a function to compare two elements of the array. This comparison function can even be a member of a class. Here's a simple example of a function to compare ints.
int intCompare(void* int1, void* int2) {
int* integer1 = (int*)int1;
int* integer2 = (int*)int2;
if (*integer1 == *integer2)
return 0;
else if (*integer1 > *integer2)
return 1;
else
return -1;
}
The function call would look like this:
int array[7] = {10, 7, 9, 4, 8, 1, 5};
sort(array, 7, sizeof(int), intCompare);
Like I said, the function works with Objects too - we can test it with this simple Circle class.
class Circle {
public:
Circle() { this->diameter = 0; };
static int circleCompare(void* c1, void* c2) {
Circle* circle1 = (Circle*)c1;
Circle* circle2 = (Circle*)c2;
if ((*circle1).diameter == (*circle2).diameter)
return 0;
else if ((*circle1).diameter > (*circle1).diameter)
return 1;
else
return -1;
}
int diameter;
};
Presuming that we assign some value to each object's diameter, we can sort the circles through a call like this:
Circle circles[7];
... diameter assignment ...
sort(circles, 7, sizeof(Circle), Circle::circleCompare);
Source
sorting.h
sorting.cpp