《高阶函数:把函数当玩具传来传去》

C++中的高阶函数

高阶函数是指可以接受其他函数作为参数或返回函数作为结果的函数。在C++中,有几种方式可以实现高阶函数的功能:

1. 函数指针

cpp 复制代码
#include <iostream>

int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }

// 高阶函数,接受函数指针作为参数
int compute(int x, int y, int (*op)(int, int)) {
    return op(x, y);
}

int main() {
    std::cout << compute(5, 3, add) << std::endl;      // 输出 8
    std::cout << compute(5, 3, subtract) << std::endl; // 输出 2
    return 0;
}

2. 函数对象(仿函数)

cpp 复制代码
#include <iostream>

// 函数对象类
struct Adder {
    int operator()(int a, int b) const {
        return a + b;
    }
};

struct Multiplier {
    int operator()(int a, int b) const {
        return a * b;
    }
};

// 高阶函数模板,接受函数对象
template <typename Operation>
int compute(int x, int y, Operation op) {
    return op(x, y);
}

int main() {
    std::cout << compute(5, 3, Adder()) << std::endl;       // 输出 8
    std::cout << compute(5, 3, Multiplier()) << std::endl;  // 输出 15
    return 0;
}

3. Lambda表达式(C++11及以上)

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>

// 高阶函数,接受lambda作为参数
void forEach(const std::vector<int>& values, void (*func)(int)) {
    for (int value : values) {
        func(value);
    }
}

int main() {
    std::vector<int> values = {1, 2, 3, 4, 5};
    
    // 使用lambda作为参数
    forEach(values, [](int value) {
        std::cout << "Value: " << value << std::endl;
    });
    
    // 使用标准库中的高阶函数
    std::sort(values.begin(), values.end(), [](int a, int b) {
        return a > b; // 降序排序
    });
    
    return 0;
}

4. std::function(C++11及以上)

cpp 复制代码
#include <iostream>
#include <functional>

int add(int a, int b) { return a + b; }

// 高阶函数,使用std::function作为参数
int compute(int x, int y, std::function<int(int, int)> op) {
    return op(x, y);
}

int main() {
    // 使用函数指针
    std::cout << compute(5, 3, add) << std::endl;
    
    // 使用lambda
    std::cout << compute(5, 3, [](int a, int b) { return a * b; }) << std::endl;
    
    // 使用函数对象
    struct Power {
        int operator()(int a, int b) const { 
            int result = 1;
            for (int i = 0; i < b; ++i) result *= a;
            return result;
        }
    };
    std::cout << compute(2, 4, Power()) << std::endl; // 2^4 = 16
    
    return 0;
}

5. 返回函数的函数

cpp 复制代码
#include <iostream>
#include <functional>

// 返回一个函数(使用lambda)
std::function<int(int)> makeAdder(int x) {
    return [x](int y) { return x + y; };
}

int main() {
    auto add5 = makeAdder(5);
    std::cout << add5(3) << std::endl; // 输出 8
    std::cout << add5(10) << std::endl; // 输出 15
    
    return 0;
}

实际应用示例

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

// 高阶函数应用:过滤器
template <typename T>
std::vector<T> filter(const std::vector<T>& vec, std::function<bool(const T&)> predicate) {
    std::vector<T> result;
    for (const auto& item : vec) {
        if (predicate(item)) {
            result.push_back(item);
        }
    }
    return result;
}

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    // 过滤偶数
    auto evens = filter<int>(numbers, [](int x) { return x % 2 == 0; });
    
    // 过滤大于5的数
    auto greaterThan5 = filter<int>(numbers, [](int x) { return x > 5; });
    
    // 输出结果
    for (auto n : evens) std::cout << n << " ";
    std::cout << std::endl;
    
    for (auto n : greaterThan5) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}

高阶函数是函数式编程的重要概念,C++通过多种机制支持这一特性,使得代码更加灵活和可复用。

相关推荐
czy878747513 分钟前
两种常见的C语言实现64位无符号整数乘以64位无符号整数的实现方法
c语言·算法
MyhEhud21 分钟前
kotlin @JvmStatic注解的作用和使用场景
开发语言·python·kotlin
虾球xz22 分钟前
游戏引擎学习第277天:稀疏实体系统
c++·学习·游戏引擎
想睡hhh26 分钟前
c++进阶——哈希表的实现
开发语言·数据结构·c++·散列表·哈希
yzx99101328 分钟前
支持向量机案例
算法·机器学习·支持向量机
行思理28 分钟前
JIT+Opcache如何配置才能达到性能最优
c++·php·jit
天上路人40 分钟前
采用AI神经网络降噪算法的语言降噪消回音处理芯片NR2049-P
深度学习·神经网络·算法·硬件架构·音视频·实时音视频·可用性测试
Clown9543 分钟前
Go语言爬虫系列教程(一) 爬虫基础入门
开发语言·爬虫·golang
南风与鱼43 分钟前
STL详解 - 红黑树模拟实现map与set
c++·红黑树封装map和set
Watermelo6171 小时前
前端如何应对精确数字运算?用BigNumber.js解决JavaScript原生Number类型在处理大数或高精度计算时的局限性
开发语言·前端·javascript·vue.js·前端框架·vue·es6