现代编译器应

本文介绍了如何使用函数指针技术实现灵活的排序算法,通过定义不同的比较函数,可以轻松地改变排序顺序(升序或降序),而无需修改排序算法本身,展示了函数指针在编程实践中的强大应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

正如你所看到的,隐式解引用的方法看起来就像一个普通的函数调用-这是你所期望的,因为正常的功能名称的函数指针吧!然而,一些老的编译器不支持隐式解引用的方法,但所有的现代编译器应。

为什么要使用函数指针?

有几种情况下,可以使用函数指针。最常见的情况是你写一个函数来执行一个任务(如数组排序),但你希望用户能够定义的任务的一个特定部分将被执行(如数组按升序或降序排序)。让我们仔细看看这个问题,专门用于排序,作为一个例子,可以推广到其他类似的问题。

所有的排序算法工作在一个类似的概念:排序算法走过一堆数字,并对数字比较,并基于这些比较的结果重新排序的数。因此,通过不同的比较(它可以是一个函数),我们可以改变函数类型不影响分类编码其余的路。

这是我们的选择排序例程从以前的教训:

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 (anArray[nCurrentIndex] < anArray[nBestIndex]) // COMPARISON DONE HERE
                nBestIndex = nCurrentIndex;
        }
 
        // Swap our start element with our best element
        swap(anArray[nStartIndex], anArray[nBestIndex]);
    }
}
现在,让我们比较函数代替做的比较。因为我们的比较函数比较两个整数并返回一个布尔值可能看起来像
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]);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值