在排序算法中,都会用到比较函数如下:
template <class T>
int Cmp(const void *a1, const void *a2)
{
T *t1 = (T*)a1;
T *t2 = (T*)a2;
return *t1 - *t2;
}
现在要求用对象中某个键值做比较,修改如下:
template <int offset, typename T>
int CmpOneKey(const void *p1, const void *p2)
{
T a1 = *(T *)((char *)p1 + offset);
T a2 = *(T *)((char *)p2 + offset);
return a1 - a2;
}
现在有一个新的需求,如果一个对象主键相等,再比较其他键值?
如何修改不影响原来的算法框架呢?
思路新比较函数比较了主键之后再比较其他键值,如下:
template <int offset1, typename T1, int offset2, typename T2>
int CmpTwoKey(const void *p1, const void *p2)
{
int diff = CmpOneKey<offset1, T1>(p1, p2);
if (diff == 0)
{
return CmpOneKey<offset2, T2>(p1, p2);
}
return diff;
}
#define cmp_one_key(s, m) CmpOneKey<offsetof(s, m), typeof(((s*)0)->m)>
#define cmp_two_key(s, m1, m2) CmpTwoKey<offsetof(s, m1), typeof(((s*)0)->m1), offsetof(s, m2), typeof(((s*)0)->m2)>