C++ 匿名函数

简介

匿名函数,简而言之,就是懒得起名字的函数。
因为,我们确实有这种需求,C++的编译器的开发者才会支持这种情况。

参考链接

https://blog.csdn.net/zhang14916/article/details/101058089

基本形式

C++中的匿名函数通常为capture->return-type{body}

capture中的类型

  • [] //未定义变量.试图在Lambda内使用任何外部变量都是错误的.
  • [x, &y] //x 按值捕获, y 按引用捕获.
  • [&] //用到的任何外部变量都隐式按引用捕获
  • [=] //用到的任何外部变量都隐式按值捕获
  • [&, x] //x显式地按值捕获. 其它变量按引用捕获
  • [=, &z] //z按引用捕获. 其它变量按值捕获
    匿名函数的结构
    parameters:存储函数的参数
    return-type:函数的返回值
    body:函数体

应用场景

  1. 当做函数指针使用
#include<iostream>
void main()
{
	int Featurea = 7;
	int Featureb = 9;
	auto fun = [](size_t Featurea, size_t Featureb){return Featurea<Featureb ? Featurea : Featureb; };
	int i = fun(Featurea, Featureb);
	std::cout << i << std::endl;
}
  1. 对一些STL容器函数sort,find等,其最后的一个参数时函数指针,我们也可以使用匿名函数来完成。比较简单的函数推荐使用匿名函数
#include<vector>
#include<algorithm>
#include<iostream>
 
void main() {
	std::vector<int> a(5);
	a[0] = 3;
	a[1] = 4;
	a[2] = 5;
	a[3] = 6;
	a[4] = 7;
	std::for_each(std::begin(a), std::end(a), [](int Feature){std::cout << Feature << std::endl; });
}
  1. 我们可以直接调用函数指针
#include<iostream>
template <class Callback>
int CollectFeatures(Callback CB)
{
	int count = 0;
	for (int i = 0; i < 10; i++)
	{
		if (CB(i))
		{
			count++;
		}
	}
	return count;
}
bool AddFeature(size_t Feature)
{
	return Feature % 2;
}
void main()
{
	
	int i = CollectFeatures([](size_t Feature) -> bool { return AddFeature(Feature); });
	std::cout << i << std::endl;
}

code

带有两个匿名参数的函数
	auto genP = [](float c = 1, float offset = 0) {
		return c * ((float)(rand() % 1800)) / 100 - c * 9;
	};

isnan函数

判断是否是一个Not-A-Number
std::isnan(v[0])

Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/13651194.html