您的位置:首页 > 其它

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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐