#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
// 使用函数式编程风格的示例代码
// 1. 使用 lambda 表达式
void use_lambda() {
// 定义一个 lambda 表达式,计算两个数的和
auto add = [](int a, int b) { return a + b; };
std::cout << "1 + 2 = " << add(1, 2) << std::endl;
}
// 2. 使用标准库中的函数对象 (functor)
struct Multiply {
int operator()(int a, int b) const {
return a * b;
}
};
void use_functor() {
Multiply multiply;
std::cout << "3 * 4 = " << multiply(3, 4) << std::endl;
}
// 3. 使用 std::function 和 std::bind
void use_std_function_and_bind() {
// 定义一个 std::function 对象,接受两个整数并返回一个整数
std::function<int(int, int)> subtract = std::minus<int>();
// 使用 std::bind 绑定一个参数
auto subtract_from_10 = std::bind(subtract, 10, std::placeholders::_1);
std::cout << "10 - 5 = " << subtract_from_10(5) << std::endl;
}
// 4. 使用高阶函数 (Higher-order functions)
void use_higher_order_function() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 使用 std::for_each 和 lambda 表达式对每个元素进行操作
std::for_each(numbers.begin(), numbers.end(), [](int& n) { n *= 2; });
// 输出结果
for (int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
}
int main() {
use_lambda();
use_functor();
use_std_function_and_bind();
use_higher_order_function();
return 0;
}
Lambda 表达式:use_lambda 函数展示了如何使用 lambda 表达式来定义匿名函数。这里定义了一个简单的加法函数,并通过 add(1, 2) 调用它。
函数对象 (Functor):use_functor 函数展示了如何定义一个函数对象(即重载了 operator() 的类)。这里定义了一个 Multiply 类,它可以像函数一样被调用。
std::function 和 std::bind:use_std_function_and_bind 函数展示了如何使用 std::function 来存储函数对象,并使用 std::bind 来绑定部分参数。这里创建了一个减法函数,并绑定了第一个参数为 10。
高阶函数:use_higher_order_function 函数展示了如何使用 C++ 标准库中的高阶函数(如 std::for_each)来对容器中的元素进行操作。这里使用了 std::for_each 和 lambda 表达式将每个元素乘以 2。
这些例子展示了 C++ 中函数式编程的基本概念和用法。
下一篇:c++ 数字转string
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站