//这是一个链表内的最小值排序算法
void CStudent::Sort()
{
POSITION p = m_list.GetHeadPosition(), q, m;
while (p)//外层循环
{
m = p;
POSITION t = p;
m_list.GetNext(t);
q = t;
while (q)//内层循环
{
if (m_list.GetAt(m).nNumber>m_list.GetAt(q).nNumber)//以学号的大小比较进行排序
{
m = q;
}
m_list.GetNext(q);
}
if (m != p)
{
DATA T = m_list.GetAt(p);
m_list.SetAt(p,m_list.GetAt(m));//m结点的数据设置到p结点里
m_list.SetAt(m, T);//先前p结点的数据设置到m结点里
}
m_list.GetNext(p);
}
}
如果是要进行更多的规则排序,这里的m_list.GetAt(m).nNumber>m_list.GetAt(q).nNumber就要进一步抽象出来,先把比较语句封装成函数并归入CStudent类中,加static关键字定义为静态的以便去除隐形this指针这个参数,固定好两个参数,按照学号、姓名字母、分数三个规则来排序,看看有没有规律:
static bool ByNum(DATA &a, DATA &b)
{
return a.nNumber>b.nNumber;
}
static bool ByNam(DATA &a, DATA &b)
{
return strcmp(a.sName, b.sName)<0;
}
static bool ByScore(DATA &a, DATA &b)
{
return a.fScore < b.fScore;
}
这里我们看到三个函数的参数个数和参数类型都是相同的,考虑到这一步,就可以很自然的和函数指针勾搭上了,下面我们定义一个函数指针:
typedef bool(*funcPointerArray)(DATA a, DATA b);
接着定义一个数组:
funcPointerArray ary[3] = { ByNum ,ByNam,ByScore };
也可以两句合并为一句:
bool(*funcPointerArray[3])(student a, student b) = { ByNum ,ByName,ByScor };还是分开来写上面两句比较容易理解
将开头的Sort函数改造一下:
void CStudent::Sort(int indext)
{
POSITION p = m_list.GetHeadPosition(), q, m;
while (p)//外层循环
{
m = p;
POSITION t = p;
m_list.GetNext(t);
q = t;
while (q)//内层循环
{
if (ary[indext -1](m_list.GetAt(m), m_list.GetAt(q)))//用函数指针类型的数组实现了排序规则
{
m = q;
}
m_list.GetNext(q);
}
if (m != p)
{
DATA T = m_list.GetAt(p);
m_list.SetAt(p, m_list.GetAt(m));//m结点的数据设置到p结点里
m_list.SetAt(m, T);//先前p结点的数据设置到m结点里
}
m_list.GetNext(p);
}
}
以上例子就是用函数指针类型的数组实现了排序规则的整个逻辑。
https://download.csdn.net/download/aidehua88/10303197,附上源代码下载地址