网易公开课,一个通用查找函数,在VC2010下实现。
#include "stdafx.h"
#include <malloc.h>
#include <string.h>
#include <malloc.h>
#include <string.h>
int lsearch( void * key, void * base,int n,int elemsize,int (*cmpfun)(void *,void *));
int intCmp(void * elem1,void * elem2);
int strCmp(void * elem1,void * elem2);
int intCmp(void * elem1,void * elem2);
int strCmp(void * elem1,void * elem2);
int _tmain(int argc, _TCHAR* argv[])
{
int key = 7;
int arr[] = {1,3,5,7,9,0};
/*int型查找*/
int ret= lsearch(&key,arr,6,sizeof(int),intCmp);
if(ret >= 0)
printf("found %d, offset is %d\n",key,ret);
else
printf("Fail\n");
{
int key = 7;
int arr[] = {1,3,5,7,9,0};
/*int型查找*/
int ret= lsearch(&key,arr,6,sizeof(int),intCmp);
if(ret >= 0)
printf("found %d, offset is %d\n",key,ret);
else
printf("Fail\n");
char skey[] = "C++";
char * sarr[] = {"C","Java","C++","Python"};
/*字符串查找*/
ret= lsearch(skey,sarr,4,sizeof(char *),strCmp);
if(ret >= 0)
printf("found %s, offset is %d\n",skey,ret);
else
printf("Fail\n");
char * sarr[] = {"C","Java","C++","Python"};
/*字符串查找*/
ret= lsearch(skey,sarr,4,sizeof(char *),strCmp);
if(ret >= 0)
printf("found %s, offset is %d\n",skey,ret);
else
printf("Fail\n");
return 0;
}
}
/*
**通用查找函数
**key:查找值
**arr:数组
**n:数组长度
**elemsize:每个元素长度
**cmpFun:比较函数
**返回值:
*/
int lsearch( void * key, void * base,int n,int elemsize,int (*cmpfun)(void *,void *))
{
for(int i=0;i<n;i++)
{
void * elemAddr = (char *)base + i*elemsize;
if(cmpfun(key,elemAddr)== 0)
return i;
**通用查找函数
**key:查找值
**arr:数组
**n:数组长度
**elemsize:每个元素长度
**cmpFun:比较函数
**返回值:
*/
int lsearch( void * key, void * base,int n,int elemsize,int (*cmpfun)(void *,void *))
{
for(int i=0;i<n;i++)
{
void * elemAddr = (char *)base + i*elemsize;
if(cmpfun(key,elemAddr)== 0)
return i;
}
return -1;
}
return -1;
}
/*
**int型比较
**返回:0-相等
*/
int intCmp(void * elem1,void * elem2)
{
int * ip1 = (int *)elem1;
int * ip2 = (int *)elem2;
return *ip1 - *ip2;
}
**int型比较
**返回:0-相等
*/
int intCmp(void * elem1,void * elem2)
{
int * ip1 = (int *)elem1;
int * ip2 = (int *)elem2;
return *ip1 - *ip2;
}
/*
**字符串型比较
**返回:0-相等
*/
int strCmp(void * elem1,void * elem2)
{
char * sp1 = (char *)elem1;
char * sp2 = *(char **)elem2;
return strcmp(sp1,sp2);
}
**字符串型比较
**返回:0-相等
*/
int strCmp(void * elem1,void * elem2)
{
char * sp1 = (char *)elem1;
char * sp2 = *(char **)elem2;
return strcmp(sp1,sp2);
}