1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include <stdio.h> #include <stdlib.h> #include <string.h>
typedef int (*CompareFunction)(const void *a, const void *b);
int compareInts(const void *a, const void *b) { int ia = *(const int*)a; int ib = *(const int*)b; return (ia > ib) - (ia < ib); }
int compareStrings(const void *a, const void *b) { return strcmp(*(const char**)a, *(const char**)b); }
int compareFloats(const void *a, const void *b) { float fa = *(const float*)a; float fb = *(const float*)b; return (fa > fb) - (fa < fb); }
void genericSort(void *base, size_t num, size_t size, CompareFunction compare) { qsort(base, num, size, compare); }
typedef void (*PrintFunction)(const void *item);
void printInt(const void *item) { printf("%d ", *(const int*)item); }
void printString(const void *item) { printf("%s ", *(const char**)item); }
void printFloat(const void *item) { printf("%.2f ", *(const float*)item); }
void printArray(const void *base, size_t num, size_t size, PrintFunction print) { const char *ptr = (const char*)base; for (size_t i = 0; i < num; i++) { print(ptr + i * size); } printf("\n"); }
void genericProgrammingExample() { printf("\n=== 泛型编程示例 ===\n"); printf("整数数组排序:\n"); int ints[] = {64, 34, 25, 12, 22, 11, 90}; int int_count = sizeof(ints) / sizeof(ints[0]); printf("排序前:"); printArray(ints, int_count, sizeof(int), printInt); genericSort(ints, int_count, sizeof(int), compareInts); printf("排序后:"); printArray(ints, int_count, sizeof(int), printInt); printf("\n字符串数组排序:\n"); const char *strings[] = {"banana", "apple", "cherry", "date"}; int str_count = sizeof(strings) / sizeof(strings[0]); printf("排序前:"); printArray(strings, str_count, sizeof(char*), printString); genericSort(strings, str_count, sizeof(char*), compareStrings); printf("排序后:"); printArray(strings, str_count, sizeof(char*), printString); printf("\n浮点数数组排序:\n"); float floats[] = {3.14f, 2.71f, 1.41f, 1.73f}; int float_count = sizeof(floats) / sizeof(floats[0]); printf("排序前:"); printArray(floats, float_count, sizeof(float), printFloat); genericSort(floats, float_count, sizeof(float), compareFloats); printf("排序后:"); printArray(floats, float_count, sizeof(float), printFloat); }
|