C++11 函数对象、Lambda表达式 & 绑定器

文章介绍了C++中的函数对象,特别是重载了operator()的类对象以及STL中的绑定器如何将二元函数对象转换为一元函数对象。接着讨论了C++11引入的`function`,它可以封装任何可调用实体,如普通函数、成员函数、Lambda表达式等。此外,文章还详细讲解了Lambda表达式的语法和用法,包括捕获外部变量的方式,以及在实际编程中的应用示例。

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

1. 函数对象和绑定器

函数对象:

重载了operator()运算符的类的对象。

STL中的原本的绑定器:

STL中的绑定器可将二元函数对象绑定为一元函数对象。有如下示例帮助回顾:

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
#include <ctime>
using namespace std;

template<typename Container>
void showContainer(Container& con) {
	/*为什么要加typename,
	因为Container是模板参数,编译器不知道Container::iterator是类型还是静态成员变量*/
	typename Container::iterator it = con.begin();
	for (; it != con.end(); ++it) {
		cout << *it << " ";
	}
	cout << endl;
}

int main(int argc, char** argv) {

	vector<int> vec;
	srand(time(nullptr));
	for (int i = 0; i < 20; i++) {
		vec.push_back(rand() % 100 + 1);
	}
	cout << "原始容器:" << endl;
	showContainer(vec);

	sort(vec.begin(), vec.end());  // 默认从小到大排序
	cout << "从小到大排序:" << endl;
	showContainer(vec);

    /*使用二元函数对象改变排序规则*/
	sort(vec.begin(), vec.end(), greater<int>());  // 从大到小
	cout << "从大到小排序:" << endl;
	showContainer(vec);

	/*将70插入到vec中,vec仍有序,即找第一个小于70的。
	需要一个一元函数对象接收70,但greater和less都是二元函数对象,
	绑定器 + 二元函数对象 = 一元函数对象
	greater:  a > b
	less:     a < b
	bind1st + greater: bool operator()(70, const _Ty& _Right)
	bind2nd + less:    bool operator()(const _Ty& _Right, 70)
	*/
	// 使用绑定器和二元函数对象greater找到第一个 < 70的元素迭代器
	auto it1 = find_if(vec.begin(), vec.end(), bind1st(greater<int>(), 70));
	if (it1 != vec.end()) {
		vec.insert(it1, 70);
	}
	cout << "70插入容器后:" << endl;
	showContainer(vec);

	system("pause");
	return 0;
}

运行结果:

5acb92371116453f83a69063bc292a1a.png


2. function

function是C++ 11提供的函数对象,它可封装任何可调用的实体,如普通函数、成员函数、Lambda表达式、函数指针等,然后可通过它封装的对象进行函数调用。

2.1 function的使用

function使用方法:

// 需要使用函数类型实例化function,而非函数指针类型。如下:
function<函数返回值类型(形参列表)> 函数对象名 = 被封装的函数名;
// 或
function<函数返回值类型(形参列表)> 函数对象名(被封装的函数名);

示例:

void hello01() {
	cout << "Hello World!" << endl;
}

void hello02(const string& str) {
	cout << str << endl;
}

int sum(int a, int b) {  // 函数指针:int (*func)(int,int);
	return a + b;
}

class Tool {
public:
	void hello(const string& str) {  // 函数指针:void (Test::*pfunc)(string&);
		cout << str << endl;
	}
};

/*function简单使用示例:*/
void test03() {
	/*需要使用函数类型实例化function,而非函数指针类型*/
	// 1.封装普通函数
	function<void()> func01 = hello01; // 使用func01函数对象表示hello01的函数类型
	func01(); // 本质是调用func01函数对象中的operator()重载,其中包装了hello01函数
	func01.operator()();

	function<void(const string&)> func02 = hello02;
	string s = "ABC";
	func02(s);

	function<int(int, int)> func03 = &sum;
	cout << func03(10, 20) << endl;

	// 2.封装Lambda表达式
	function<int(int, int)> func04 = [](int a, int b)->int {
		return a * b;
	};
	cout << func04(6, 6) << endl;

	// 3.封装成员函数
	/*成员函数会带this指针参数,即调用它的对象的类型的指针*/
	function<void(unique_ptr<Tool>, const string&)> func05 = &Tool::hello;
	unique_ptr<Tool> p(new Tool());
	func05(std::move(p), string("func05"));  // 第二个参数是临时量,临时量可传给常量引用,但不可传给非常量引用
}

2.2 function的原理

在此之前,需要知道什么是模板特例化

function主要原理如下两个程序:

2.2.1 实现简单的myfunction

template<typename T>
class myfunction {};

template<typename R, typename A>
class myfunction<R(A)> {
public:
	using PFUNC = R(*)(A);
	myfunction(PFUNC pf) :_pf(pf) {
	}
	R operator()(A arg) {
		_pf(arg);
	}
private:
	PFUNC _pf;
};

void hello01(string s) {
	cout << s << endl;
}

void test06() {
	myfunction<void(string)> func01 = hello01;
	string s = "AAA";
	func01(s);  // AAA
}

但上述自己实现的function对象只能接收固定形参个数的函数。

2.2.2 使用可变参模板改进myfunction

template<typename T>
class myfunction {};

template<typename R, typename... A>  // ...表示可变参
class myfunction<R(A...)> {
public:
	using PFUNC = R(*)(A...);
	myfunction(PFUNC pf) :_pf(pf) {
	}
	R operator()(A... arg) {
		return _pf(arg...);
	}
private:
	PFUNC _pf;
};

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

void say() {
	cout << "哈哈" << endl;
}

bool isIt(const char* s) {
	return s;
}

void test07() {
	myfunction<int(int, int, int)> addFunc(add);
	cout << addFunc(1, 2, 3) << endl;  // 6

	myfunction<void()> sayFunc = say;
	sayFunc();  // 哈哈

	myfunction<bool(const char*)> boolFunc(isIt);
	cout << boolFunc("000") << endl;   // 1
	cout << boolFunc(nullptr) << endl; // 0
}

改进后的myfunction就十分嚣张,可指定任意返回值类型、任意形参列表。


3. 绑定器的原理和简单实现

绑定器:将多元函数对象的个别参数提前绑定,使得多元函数对象成为低元函数对象。本质也是函数对象。

3.1 STL中find_if和bind1st的简单实现

/*自己实现find_if泛型算法*/
template<typename Iterator, typename Compare>
Iterator my_find_if(Iterator first, Iterator last, Compare comp) {
	for (; first != last; ++first) {
		if (comp(*first)) { // comp.operator()(*first)
			return first;
		}
	}
	return last;
}

/*自己实现绑定器*/
template<typename Compare, typename T>
class _mybind1st {
public:
	_mybind1st(Compare comp, T val) :_comp(comp), _val(val) {
	}
	bool operator()(const T& second) {
		return _comp(_val, second);
	}
private:
	Compare _comp;
	T _val;
};

template<typename Compare, typename T>
_mybind1st<Compare, T> mybind1st(Compare comp, const T& val) {
	// 函数模板可进行类型推导
	return _mybind1st<Compare, T>(comp, val);
}

void test02() {
	vector<int> vec2;
	vec2.push_back(5);
	vec2.push_back(3);
	vec2.push_back(9);

	// 找第一个 < 6的元素
	auto it = my_find_if(vec2.begin(), vec2.end(), mybind1st(greater<int>(), 6));
	if (it != vec2.end()) {
		cout << *it << endl;
	} else {
		cout << "没找到" << endl;
	}
}

3.2 C++ 11绑定器bind

bind是函数模板,可自动推导模板参数类型,其返回一个函数对象。

3.2.1 绑定器的简单使用

int divide(int a, int b) { 
    return a / b; 
}

class M {
public:
	int sum(int a, int b) { 
        return a + b; 
    }
};

void test08() {
    /*给普通函数绑定参数*/
	auto ret = bind(divide, 100, 50)();
	cout << ret << endl;

    /*给成员函数绑定参数*/
	cout << bind(&M::sum, M(), 5, 10)() << endl; // 15
}

注意:成员函数的调用依赖对象,因此绑定成员函数时第二个参数为临时对象,以传给sum函数,相当于M().sum(5, 10)。

3.2.2 绑定器的参数占位符

使用如下:

void speak(const char* s) {
	cout << s << endl;
}

void test09() {
	char input[64] = "";
	cin >> input;  // 输入内容
	bind(speak, placeholders::_1)(input);  // 打印内容
}

注意:(1)绑定器若使用参数占位符,则必须给其返回的函数对象的operator()运算符传入参数,让其内部传给占位参数;

           (2)最多可有20个参数占位符;

           (3)参数占位符一般是让程序运行过程中动态传递参数。


3.3 bind与function

3.2中bind的使用存在一个问题,bind调用一次,其返回的函数对象只能执行一次,若想多次使用,则可将bind返回的函数对象传给function函数对象。

如下:

void speak(const char* s) {
	cout << s << endl;
}

void test10() {
	function<void(const char*)> speakFunc = bind(speak, placeholders::_1);
	speakFunc("LLL"); // LLL
	speakFunc("UUU"); // UUU
}

4. Lambda表达式

也称为匿名函数,是一种特殊的函数对象。

4.1 Lambda表达式的语法

[捕获外部变量](形参列表)->返回值类型 {
    // 函数主体
}

/*
    1. 若返回值类型为void,则 ->void 可省略;
    
    2. [捕获外部变量]:
            [=]:值传递方式捕获外部所有变量;
            [&]:引用传递方式捕获外部所有变量;
            [this]:捕获外部this指针;
            [=, &a]:值传递方式捕获外部变量,但a以引用传递方式捕获;
            [a, b]:值传递方式捕获a,b;
            [a, &b]:值传递方式捕获a,引用传递方式捕获b
*/

4.2 Lambda表达式简单使用

4.2.1 简单使用1

输出Hello

void test() {
	auto func = []() {
		cout << "Hello" << endl;
	};
	func();  // Hello
}

作用和下面定义函数对象相同:

class TestLambda {
public:
	void operator()() {
		cout << "Hello" << endl;
	}
};

void test() {
    // 根据最短惊叹法则,写成TestLambda t1(); 则编译认为这是一个函数的声明
    TestLambda t1{};  
	t1();
}

4.2.2 简单使用2

加法运算

void test() {
	auto func = [](int a, int b)->int {
		return a + b;
	};
	cout << func(10, 20) << endl;  // 30
}

4.2.3 简单使用3 

容器排序 & 插入元素

void printVector(vector<int>& v) {
	for (int i = 0; i < v.size(); i++) {
		cout << v[i] << " ";
	}
	cout << endl;
}

void test14() {
	vector<int> v;
	for (int i = 0; i < 10; i++) {
		v.push_back(rand() % 100 + 1);
	}

	cout << "排序前:" << endl;
	printVector(v);

	/*从大到小排序*/
	sort(v.begin(), v.end(), [](int a, int b)->bool {
		return a > b;
		});
	cout << "排序后:" << endl;
	printVector(v);

	/*将66插入正确位置*/
	auto it = find_if(v.begin(), v.end(), [](int a)->bool {
		return a < 66;
		});
	v.insert(it, 66);
	cout << "插入66后:" << endl;
	printVector(v);

	/*输出大于50的数*/
	cout << "大于50的数:" << endl;
	for_each(v.begin(), v.end(), [](int a) {
		if (a > 50)
			cout << a << " ";
		});
}

运行结果:

8279962773f14e22b9e3ce832cd93330.png


4.3 Lambda表达式捕获外部变量

4.3.1 值传递 和 引用传递简单使用

/*值传递捕获a、b*/
void test13() {
	int a = 10, b = 20;
	auto func = [=]() {
		cout << a + b << endl;
	};
	func(); // 30
}

/*引用传递捕获a、b*/
void test13() {
	int a = 10, b = 20;
	auto func = [&]() {
		cout << a + b << endl;
	};
	func(); // 30
}

4.3.2 值传递 和 引用传递使用说明

(1)引用传递

引用传递可以直接修改外部变量的值。

void test13() {
	int a = 10, b = 20;
	auto func = [&]() {
		a = 88;
		b = 99;
	};

	func(); // 引用传递可以改变原变量的值
	cout << "a = " << a << ", b = " << b << endl; // a和b都被修改
}

(2)值传递

值传递是外部变量的一份拷贝,虽然是拷贝,但默认不允许修改拷贝过来的值。

如下代码无法通过编译:

void test13() {
	int a = 10, b = 20;
	auto func = [=]() {
		a = 88; // 报错!不允许修改。
		b = 99; // 报错!不允许修改。
	};
}

若想修改拷贝而来的值,则需使用mutable关键字,如下:

void test13() {
	int a = 10, b = 20;
	auto func = [=]() mutable {
		a = 88;
		b = 99;
	};

	func(); // 值传递不改变原变量的值
	cout << "a = " << a << ", b = " << b << endl; // a和b都未被修改
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伟大的马师兄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值