C++ 可调用对象的总结

C++总共有5种可调用对象: 普通函数, 函数指针, lambda, 函数对象(仿函数), bind创建的对象(主要将多元谓词降次)

具体代码如下:

#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
using namespace std;
using namespace std::placeholders;//can't use std only

const int NUM = 40;
/*c++ has 5 kinds of callable objects*/
//1
auto f = [](int &a) { a = a * a; };//lambda

//2
void callable (int &a, int b)
{
	if (a * a < b)// if the square of a is less than b, then square it
	{
		a = a * a;
	}
};
// note: use fuctional header and placeholders namespace before bind
auto call = bind(callable, _1, NUM);//bind

//3
void square(int &a)//ordinary function
{
	a = a * a;
}

//4
void(*p)(int &a) = square;//function pointer
auto p1 = □//we can use auto in a easy way: p1 == p

//5
//function object: class that overload the function-call operator
struct PrintInt//function-object or functor
{
	void operator()(int elem)
	{
		cout << elem << " ";
	}
};

int main()
{
	vector<int> v1{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	vector<int> v2{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	vector<int> v3{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	vector<int> v4{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	for_each(v1.begin(), v1.end(), f);
	for_each(v2.begin(), v2.end(), square);
	for_each(v3.begin(), v3.end(), p);
	//for_each(v3.begin(), v3.end(), p1);
	for_each(v4.begin(), v4.end(), call);
	for_each(v3.crbegin(), v3.crend(), [](int elem) { cout << elem << " "; });
	cout << endl;
	for_each(v3.cbegin(), v3.cend(), PrintInt());//don't lose "()"
	cout << endl;
	for_each(v4.cbegin(), v4.cend(), PrintInt());
	cout << endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值