C Tips: 比较函数 int(*cmp)(const void *, const void *)
2014-04-05 17:22
393 查看
C语言中,一个通用的比较函数的指针,可以表示为:
int(*cmp)(const void *, const void *)
对于它我们可以有各种各样的实现。
比如说,对于这样的一个结构体的定义:
struct ItemStruct
{
unsigned __int16 HeadwareId;
unsigned __int16 RangeId;
};
typedef struct ItemStruct Item;
我们可以写出以下这样的比较函数:
int cmpItems(const void * a, const void * b)
{
if (a == NULL && b == NULL)
{
return 0;
}
else if (a == NULL && b != NULL)
{
return -1;
}
else if (a != NULL && b == NULL)
{
return 1;
}
return cmpItemsValue(*(const Item *)&a, *(const Item *)&b);
}
int cmpItemsValue(const Item a, const Item b)
{
if (a.HeadwareId > b.HeadwareId)
{
return 1;
}
else if (a.HeadwareId < b.HeadwareId)
{
return -1;
}
else
{
if (a.RangeId > b.RangeId)
{
return 1;
}
else if (a.RangeId < b.RangeId)
{
return -1;
}
else
{
return 0;
}
}
}
int(*cmp)(const void *, const void *)
对于它我们可以有各种各样的实现。
比如说,对于这样的一个结构体的定义:
struct ItemStruct
{
unsigned __int16 HeadwareId;
unsigned __int16 RangeId;
};
typedef struct ItemStruct Item;
我们可以写出以下这样的比较函数:
int cmpItems(const void * a, const void * b)
{
if (a == NULL && b == NULL)
{
return 0;
}
else if (a == NULL && b != NULL)
{
return -1;
}
else if (a != NULL && b == NULL)
{
return 1;
}
return cmpItemsValue(*(const Item *)&a, *(const Item *)&b);
}
int cmpItemsValue(const Item a, const Item b)
{
if (a.HeadwareId > b.HeadwareId)
{
return 1;
}
else if (a.HeadwareId < b.HeadwareId)
{
return -1;
}
else
{
if (a.RangeId > b.RangeId)
{
return 1;
}
else if (a.RangeId < b.RangeId)
{
return -1;
}
else
{
return 0;
}
}
}
相关文章推荐
- static int getch(void)函数中的if(!isatty(STDIN_FILENO)详解
- void定义函数与int、double的区别
- LeetCode/sort(地址A,地址B)和qsort(首地址,元素个数,sizeof(),cmp比较函数)的使用
- C++ 使用STL时自定义比较函数cmp
- 实现内存复制函数void * memcpy(void *dst,void *src,int count).
- FAQ: c++ 函数名后添加 const void function1(int &id) const
- 基于PHP字符串的比较函数strcmp()与strcasecmp()的使用详解
- 用C语言实现函数void * memmove(void *dest, const void *src, size_t n)。
- error C2556: 'void __thiscall ::sendCommand1(unsigned int,const char *,int)' : overloaded function differs only by return type f
- 无法解析的外部符号 WinMain,该符号在函数 "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) 中被引用
- void (*f(int, void (*)(int)))(int) 函数解析
- 对于这个函数const int func(const int& a) const声明中,三个const分别是什么意思?
- 用C语言实现函数void * memmove(void *dest,const void *src,size_t n)
- 编写函数void count(char a[],char w[][10],int n,int b[])。功能是:统计w指向的数组中的n个单词在a指向的字符串中各自出现的次数(将非字母字符看作单词分
- static int getch(void)函数中的if(!isatty(STDIN_FILENO)详解
- 快速排序,void Qsort(void *base,int nelem,int width, int (*fcmp)(const void *,const void *))的实现。
- void (*f(int, void (*)(int)))(int) 函数解析
- void (*f(int, void (*)(int)))(int) 函数解析
- Python的内建比较函数cmp比较原理剖析
- 【c++】 sort的cmp函数的string的比较大小