【C++】C++11 (3): lambda表达式和包装器

一、lambda表达式

  • C++98中的一个例子
    在C++98中,如果想要对一个数据集合中的元素进行排序,可以使用std::sort方法。
cpp 复制代码
#include <algorithm>
#include <functional>
int main()
{
	int a[] = { 4,1,8,5,3,7,0,9,2,6 };
	// 默认按照小于比较,排出来结果是升序
	std::sort(a, a + sizeof(a) / sizeof(a[0]));
	// 如果需要降序,需要改变元素的比较规则
	std::sort(a, a + sizeof(a) / sizeof(a[0]), std::greater<int>());
	return 0;
}

如果待排序元素为自定义类型,需要用户定义排序时的比较规则:

cpp 复制代码
struct Goods
{
	string _name; // 名字
	double _price; // 价格
	int _evaluate; // 评价
	Goods(const char* str, double price, int evaluate)
		:_name(str),
		_price(price),
		_evaluate(evaluate)
	{}
};
struct ComparePriceLess
{
	bool operator()(const Goods& gl, const Goods& gr)
	{
		return gl._price < gr._price;
	}
};
struct ComparePriceGreater
{
	bool operator()(const Goods& gl, const Goods& gr)
	{
		return gl._price > gr._price;
	}
};
int main()
{
	vector<Goods> v = { { "apple", 1.0, 5 }, { "banana", 3, 4 }, 
				{ "orange", 2.2, 3 }, { "pineapple", 1.5, 4 } };
	sort(v.begin(), v.end(), ComparePriceLess());
	sort(v.begin(), v.end(), ComparePriceGreater());
}

上面的写法太复杂了,每次为了实现一个algorithm算法, 都要重新去写一个类。如果每次比较的逻辑不一样,还要去实现多个类,特别是相同类的命名,这些都带来了极大的不便。因此,在C++11语法中出现了Lambda表达式。

cpp 复制代码
int main()
{
	vector<Goods> v = { { "apple", 1.0, 5 }, { "banana", 3, 4 },
				{ "orange", 2.2, 3 }, { "pineapple", 1.5, 4 } };
	sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
		return g1._price < g2._price;
	});
	sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
		return g1._price > g2._price;
	});
	sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
		return g1._evaluate < g2._evaluate;
	});
	sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
		return g1._evaluate > g2._evaluate;
	});
}

上述代码就是使用C++11中的lambda表达式来解决,可以看出lambda表达式实际是一个匿名函数

1. lambda表达式语法

lambda表达式书写格式:[capture-list] (parameters) mutable -> return-type { statement }

-lambda表达式各部分说明

  1. [capture-list] : 捕捉列表,该列表总是出现在lambda函数的开始位置,编译器根据[]来 判断接下来的代码是否为lambda函数,捕捉列表能够捕捉上文中的变量供lambda 函数使用。
  2. (parameters):参数列表。与普通函数的参数列表一致,如果不需要参数传递,则可以 连同()一起省略
  3. mutable:默认情况下,lambda函数总是一个const函数,mutable可以取消其常量性。使用该修饰符时,参数列表不可省略(即参数为空)。
  4. ->return-type:返回值类型。用追踪返回类型形式声明函数的返回值类型,没有返回 值时此部分可省略。返回值类型明确情况下,也可省略,由编译器对返回类型进行推导。
  5. {statement}:函数体。在该函数体内,除了可以使用其参数外,还可以使用所有捕获 到的变量。

注意:

在lambda函数定义中,参数列表和返回值类型都是可选部分,而捕捉列表和函数体可以为空。

因此C++11中最简单的lambda函数为:[]{}; 该lambda函数不能做任何事情。

cpp 复制代码
int main()
{
	// 最简单的lambda表达式, 该lambda表达式没有任何意义
	[] {};
	// 省略参数列表和返回值类型,返回值类型由编译器推导为int
	int a = 3, b = 4;
	[=] {
		return a + 3;
	};
	// 省略了返回值类型,无返回值类型
	auto fun1 = [&](int c) {
		b = a + c;
	};
	fun1(10);
	cout << a << " " << b << endl;
	// 各部分都很完善的lambda函数
	auto fun2 = [=, &b](int c)->int {
		return b += a + c;
	};
	cout << fun2(10) << endl;
	// 复制捕捉x
	int x = 10;
	auto add_x = [x](int a) mutable {
		x *= 2;
		return a + x;
	};
	cout << add_x(10) << endl;
	return 0;
}

通过上述例子可以看出,lambda表达式实际上可以理解为无名函数,该函数无法直接调 用,如果想要直接调用,可借助auto将其赋值给一个变量。

2. 捕获列表说明

捕捉列表描述了上下文中那些数据可以被lambda使用,以及使用的方式传值还是传引用。

  1. [var]:表示值传递方式捕捉变量var
  2. [=]:表示值传递方式捕获所有父作用域中的变量(包括this)
  3. [&var]:表示引用传递捕捉变量var
  4. [&]:表示引用传递捕捉所有父作用域中的变量(包括this)
  5. [this]:表示值传递方式捕捉当前的this指针

注意:

  • 父作用域指包含lambda函数的语句块
  • 语法上捕捉列表可由多个捕捉项组成,并以逗号分割。
  • 比如:[=, &a, &b]表示以引用传递的方式捕捉变量a和b,值传递方式捕捉其他所有变量
  • [&,a, this]:值传递方式捕捉变量a和this,引用方式捕捉其他变量
  • 捕捉列表不允许变量重复传递,否则就会导致编译错误。
  • 比如:[=, a]:=已经以值传递方式捕捉了所有变量,捕捉a重复
  • 在块作用域以外的lambda函数捕捉列表必须为空。
  • 在块作用域中的lambda函数仅能捕捉父作用域中局部变量,捕捉任何非此作用域 或者 非局部变量都会导致编译报错。
  • lambda表达式之间不能相互赋值,即使看起来类型相同
cpp 复制代码
void (*PF)();
int main()
{
	auto f1 = [] {cout << "hello world" << endl; };
	auto f2 = [] {cout << "hello world" << endl; };
	// 此处先不解释原因,等lambda表达式底层实现原理看完后,大家就清楚了
	//f1 = f2;    // 编译失败--->提示找不到operator=()
	// 允许使用一个lambda表达式拷贝构造一个新的副本
	auto f3(f2);
	f3();
	// 可以将lambda表达式赋值给相同类型的函数指针
	PF = f2;
	PF();
	return 0;
}

3. 函数对象与lambda表达式

函数对象,又称为仿函数,即可以像函数一样使用的对象,就是在类中重载了operator()运算符的类对象

cpp 复制代码
class Rate
{
public:
	Rate(double rate) : _rate(rate)
	{}
	double operator()(double money, int year)
	{
		return money * _rate * year;
	}
private:
	double _rate;
};
int main()
{
	// 函数对象
	double rate = 0.49;
	Rate r1(rate);
	r1(10000, 2);
	// lambda
	auto r2 = [=](double monty, int year)->double {
		return monty * rate * year;
	};
	r2(10000, 2);
	return 0;
}

从使用方式上来看,函数对象与lambda表达式完全一样。

函数对象将rate作为其成员变量,在定义对象时给出初始值即可,lambda表达式通过捕获列表可以直接将该变量捕获到。

实际在底层编译器对于lambda表达式的处理方式,完全就是按照函数对象的方式处理的,即:如果定义了一个lambda表达式,编译器会自动生成一个类,在该类中重载了operator()。


二、包装器

1. function

function包装器,也可以叫作适配器。C++中的function本质是一个类模板,也是一个包装器。 那么我们为什么需要function呢?

ret = func(x);func可能是什么呢?

func可能是函数名?函数指针?函数对象(仿函数对象)?也有可能是lambda表达式对象?这些都是可调用的类型!如此丰富的类型,可能会导致模板的效率低下!

为什么呢?我们继续往下看

cpp 复制代码
template<class F, class T>
T useF(F f, T x)
{
	static int count = 0;
	cout << "count:" << ++count << endl;
	cout << "count:" << &count << endl;
	return f(x);// 返回x计算后的值
}
double f(double i)
{
	return i / 2;
}
struct Functor
{
	double operator()(double d)
	{
		return d / 3;
	}
};
int main()
{
	// 函数名
	cout << useF(f, 11.11) << endl;
	// 函数对象
	cout << useF(Functor(), 11.11) << endl;
	// lambda表达式
	cout << useF([](double d)->double { return d / 4; }, 11.11) << endl;
	return 0;
}

通过上面的程序验证,我们会发现useF函数模板实例化了三份(count有三个不同地址)。

包装器可以很好的解决上面的问题

std::function在头文件<functional>

模板参数说明:

Ret: 被调用函数的返回类型

Args...:被调用函数的形参

使用方法如下:

cpp 复制代码
#include <functional>
int f(int a, int b)
{
	return a + b;
}
struct Functor
{
public:
	int operator() (int a, int b) {
		return a + b;
	}
};
class Plus
{
public:
	static int plusi(int a, int b)
	{
		return a + b;
	}
	double plusd(double a, double b)
	{
		return a + b;
	}
};
int main()
{
	// 函数名(函数指针)
	std::function<int(int, int)> func1 = f;
	cout << func1(1, 2) << endl;
	// 函数对象
	std::function<int(int, int)> func2 = Functor();
	cout << func2(1, 2) << endl;
	// lambda表达式
	std::function<int(int, int)> func3 = [](const int a, const int b) {
		return a + b;
	};
	cout << func3(1, 2) << endl;
	// 类的成员函数
	// 静态成员函数可以不加 &
	std::function<int(int, int)> func4 = &Plus::plusi;
	cout << func4(1, 2) << endl;
	// 注意有this参数
	std::function<double(Plus, double, double)> func5 = &Plus::plusd;
	cout << func5(Plus(), 1.1, 2.2) << endl;
	return 0;
}

有了包装器,如何解决模板的效率低下,实例化多份的问题呢?

cpp 复制代码
#include <functional>
template<class F, class T>
T useF(F f, T x)
{
	static int count = 0;
	cout << "count:" << ++count << endl;
	cout << "count:" << &count << endl;
	return f(x);
}
double f(double i)
{
	return i / 2;
}
struct Functor
{
	double operator()(double d)
	{
		return d / 3;
	}
};
int main()
{
	// 函数名
	std::function<double(double)> func1 = f;
	cout << useF(func1, 11.11) << endl;
	// 函数对象
	std::function<double(double)> func2 = Functor();
	cout << useF(func2, 11.11) << endl;
	// lambda表达式
	std::function<double(double)> func3 = [](double d)->double {
		return d / 4;
	};
	cout << useF(func3, 11.11) << endl;
	return 0;
}

包装器对这些可调用对象的类型进行了统一,useF只实例化了一份,三次调用的都是同一份。

包装器的其他一些场景:
逆波兰表达式求值

cpp 复制代码
class Solution {
public:
	int evalRPN(vector<string>& tokens) {
		stack<int> st;
		for (auto& str : tokens) {
			if (str == "+" || str == "-"
				|| str == "*" || str == "/") {
				int right = st.top(); st.pop();
				int left = st.top(); st.pop();
				switch (str[0]) {
				case '+':
					st.push(left + right);
					break;
				case '-':
					st.push(left - right);
					break;
				case '*':
					st.push(left * right);
					break;
				case '/':
					st.push(left / right);
					break;
				}
			}
			else
			{
				st.push(stoi(str));
			}
		}
		return st.top();
	}
};

使用包装器后:

cpp 复制代码
class Solution {
public:
	int evalRPN(vector<string>& tokens) {
		stack<int> st;
		map<string, function<int(int, int)>> opFuncMap = {
			{ "+",  [](int i, int j) {return i + j; } }, 
			{ "-",  [](int i, int j) {return i - j; } }, 
			{ "*",  [](int i, int j) {return i * j; } }, 
			{ "/",  [](int i, int j) {return i / j; } } 
		};
		for (auto& str : tokens) {
			if (opFuncMap.find(str) != opFuncMap.end()) {
				int right = st.top(); st.pop(); 
				int left = st.top(); st.pop();
				st.push(opFuncMap[str](left, right));
			} else {
				st.push(stoi(str));
			}
		}
		return st.top();
	}
};

2. bind

std::bind函数定义在functional头文件中,是一个函数模板,它就像一个函数包装器(适配器),接受一个可 调用对象(callable object),生成一个新的可调用对象来"适应"原对象的参数列表。

一般而 言,我们用它可以把一个原本接收N个参数的函数fn,通过绑定一些参数,返回一个接收M个(M 可以大于N,但这么做没什么意义)参数的新函数。同时,使用std::bind函数还可以实现参数顺 序调整等操作。

cpp 复制代码
// 原型如下:
template <class Fn, class... Args>
/* unspecified */ bind (Fn&& fn, Args&&... args);

template <class Ret, class Fn, class... Args>
/* unspecified */ bind (Fn&& fn, Args&&... args);

可以将 bind 函数看作是一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对象来"适应"原对象的参数列表。

调用bind的一般形式:auto newCallable = bind(callable,arg_list);

其中,newCallable 本身是一个可调用对象,arg_list 是一个逗号分隔的参数列表,对应给定的 callable 的参数。

当我们调用 newCallable 时,newCallable 会调用 callable,并传给它 arg_list 中

的参数。arg_list 中的参数可能包含形如_n的名字,其中n是一个整数,这些参数是"占位符",表示 newCallable 的参数,它们占据了传递给 newCallable 的参数的"位置"。数值n表示生成的可调用对 象中参数的位置:_1为 newCallable 的第一个参数,_2为第二个参数,以此类推。

cpp 复制代码
// 使用举例
#include <functional>
int Plus(int a, int b)
{
	return a + b;
}
class Sub
{
public:
	int sub(int a, int b)
	{
		return a - b;
	}
};
int main()
{
	// 表示绑定函数Plus 参数分别由调用 func1 的第一,二个参数指定
	std::function<int(int, int)> func1 = std::bind(Plus, placeholders::_1, placeholders::_2);
	//auto func1 = std::bind(Plus, placeholders::_1, placeholders::_2);
	// func2的类型为 function<void(int, int, int)> 与func1类型一样
	// 表示绑定函数 Plus 的第一,二为: 1, 2
	auto func2 = std::bind(Plus, 1, 2);
	cout << func1(1, 2) << endl;
	cout << func2() << endl;

	Sub s;
	// 绑定成员函数
	std::function<int(int, int)> func3 = std::bind(&Sub::sub, s, placeholders::_1, placeholders::_2);
	// 参数调换顺序
	std::function<int(int, int)> func4 = std::bind(&Sub::sub, s, placeholders::_2, placeholders::_1);
	cout << func3(1, 2) << endl;// 1 - 2
	cout << func4(1, 2) << endl;// 2 - 1
	return 0;
}

通过使用 bind 函数,我们可以创建灵活的函数对象,方便地进行参数控制和函数重用。


相关推荐
BeyondESH32 分钟前
Linux线程同步—竞态条件和互斥锁(C语言)
linux·服务器·c++
豆浩宇42 分钟前
Halcon OCR检测 免训练版
c++·人工智能·opencv·算法·计算机视觉·ocr
WG_171 小时前
C++多态
开发语言·c++·面试
Charles Ray2 小时前
C++学习笔记 —— 内存分配 new
c++·笔记·学习
重生之我在20年代敲代码2 小时前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
迷迭所归处8 小时前
C++ —— 关于vector
开发语言·c++·算法
CV工程师小林9 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
white__ice9 小时前
2024.9.19
c++
天玑y9 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
姜太公钓鲸23310 小时前
c++ static(详解)
开发语言·c++