泛型编程让你编写完全一般化并可重复使用的算法,其效率与针对某特定数据类型而设计的算法相同。 这里提供一种方法,通过空指针类型void*
现交换两个元素内容的函数 swap
#include <stdio.h>
void swap(void *arg1, void *arg2, unsigned type)
{
char temp = 0;
char *p1 = (char*)arg1;
char *p2 = (char*)arg2;
while(type--)
{
temp = *p1;
*p1 = *p2;
*p2 = temp;
p1++;
p2++;
}
}
int main()
{
int arg1 = 0x11223344;
int arg2 = 0x55667788;
printf("arg1 = %X arg2 = %X\n", arg1, arg2);
swap(&arg1, &arg2, sizeof(arg1));
printf("arg1 = %X arg2 = %X\n", arg1, arg2);
}
在数组中查询元素,找到则返回它的索引,没找到返回-1
#include <stdio.h>
int lmemcmp(void *mem1, void*mem2, unsigned type)
{
char *p1 = 0;
char *p2 = 0;
p1 = (char*)mem1;
p2 = (char*)mem2;
while(type--)
{
if(*p1 != *p2)
{
return -1;
}
p1++;
p2++;
}
return 0;
}
int lsearch(void *key, void *buff, unsigned type, unsigned count)
{
void *p = NULL;
for(unsigned i = 0; i < count; i++)
{
p = buff + i * type;
if(lmemcmp(key, p, type) == 0)
return i;
}
return -1;
}
int main()
{
int buff[] = {1,2,3,4,5,6,7,8};
int i = 8;
printf("%d\n", lsearch(&i, buff, sizeof(*buff), sizeof(buff) / sizeof(*buff)));
}
C 语言也可以实现一定的泛型编程,但这样是不安全的,系统对其只有有限的检查。在编程时一定要多加细心。
|