The qsort library function that actually does the sort takes four arguments: a pointer to the beginning of the array, the number of objects, the size of each object, and a comparison function. It achieves independence from the type of object being sorted by blindly rearranging the blocks of data that represent objects (in this case string pointers) and by using a comparison function that takes pointers to void as argument. This code casts these back to type pointer to pointer to char for strcmp. To actually access the first character in a string for a comparison, we dereference three pointers: one to get the index (which is a pointer) into our array, one to get the pointer to the string (using the index), and one to get the character (using the pointer).
We use a different method to achieve type independence for our sorting and searching functions (see Chapters 4 and 6).
#include
#include
#include
int compare(const void *i, const void *j)
{ return strcmp(*(char **)i, *(char **)j); }
int main()
{ const int Nmax = 1000;
const int Mmax = 10000;
char* a[Nmax]; int N;
char buf[Mmax]; int M = 0;
for (N = 0; N < Nmax; N++)
{
a[N] = &buf[M];
if (!(cin >> a[N])) break;
M += strlen(a[N])+1;
}
qsort(a, N, sizeof(char*), compare);
for (int i = 0; i < N; i++)
cout << a[i] << endl;
}
Комментариев нет:
Отправить комментарий