现在,让我们比较函数代替做的比较。
因为我们的
比较函数
来
比较两个
整数
并返回
一个布尔值
,
它
可能看起来像
:
这是 我们的 选择排序 例程使用 ascending() 功能 做的比较 :|
1
2
3
4
bool Ascending(int nX, int nY)
{
return nY > nX;
}
这是 我们的 选择排序 例程使用 ascending() 功能 做的比较 :|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void SelectionSort(int *anArray, int nSize)
{
using namespace std;
for (int nStartIndex= 0; nStartIndex < nSize; nStartIndex++)
{
int nBestIndex = nStartIndex;
// Search through every element starting at nStartIndex+1
for (int nCurrentIndex = nStartIndex + 1; nCurrentIndex < nSize; nCurrentIndex++)
{
// Note that we are using the user-defined comparison here
if (Ascending(anArray[nCurrentIndex], anArray[nBestIndex])) // COMPARISON DONE HERE
nBestIndex = nCurrentIndex;
}
// Swap our start element with our best element
swap(anArray[nStartIndex], anArray[nBestIndex]);
}
}
为了让对方决定如何排序来完成,而不是用我们自己的硬编码的比较函数,我们将允许调用者提供自己的排序功能!这是通过一个函数指针。
由于呼叫者的比较函数来比较两个整数并返回一个布尔值,一个指向这样的功能可能会是这样子的:
1
bool (*pComparison)(int, int);
因此,我们将允许调用者通过我们的排序例程的指针到期望的比较函数的第三个参数,然后我们再利用对方的功能做的比较。
这是一个选择排序,使用函数指针参数做一个用户自定义的比较完整的例子,以及一个示例如何调用它: