用c实现compare通用接口
时间: 2024-04-21 20:22:39 浏览: 20
以下是一个用 C 语言实现通用比较接口的示例:
```c
#include <stdio.h>
// 定义通用比较接口
typedef int (*CompareFunc)(void* a, void* b);
// 整数比较函数
int compareInt(void* a, void* b) {
int num1 = *((int*)a);
int num2 = *((int*)b);
return num1 - num2;
}
// 浮点数比较函数
int compareFloat(void* a, void* b) {
float num1 = *((float*)a);
float num2 = *((float*)b);
if (num1 < num2) return -1;
if (num1 > num2) return 1;
return 0;
}
// 字符串比较函数
int compareString(void* a, void* b) {
char* str1 = (char*)a;
char* str2 = (char*)b;
return strcmp(str1, str2);
}
// 示例使用
int main() {
int a = 10, b = 20;
float c = 3.14, d = 2.71;
char str1[] = "Hello";
char str2[] = "World";
// 使用整数比较函数
CompareFunc cmpInt = compareInt;
int result1 = cmpInt(&a, &b);
printf("Integer comparison: %d\n", result1);
// 使用浮点数比较函数
CompareFunc cmpFloat = compareFloat;
int result2 = cmpFloat(&c, &d);
printf("Float comparison: %d\n", result2);
// 使用字符串比较函数
CompareFunc cmpString = compareString;
int result3 = cmpString(str1, str2);
printf("String comparison: %d\n", result3);
return 0;
}
```
上述示例中,通过 `typedef` 定义了一个函数指针类型 `CompareFunc`,该函数指针类型可以指向任意比较函数。然后分别实现了整数、浮点数和字符串的比较函数,并在 `main` 函数中进行了示例使用。
注意在比较函数中,需要将指针参数转换为相应的类型,然后进行比较操作。比较函数需要返回一个整数值,表示两个参数的大小关系。正数表示第一个参数大于第二个参数,负数表示第一个参数小于第二个参数,零表示两个参数相等。
这只是一个简单的示例,你可以根据具体需求在此基础上进行扩展和优化。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)