lambda函数表达式 和 数组索引表达式

lambda: 

参考:

C++11:lambda表达式_lambda表达式c++11-CSDN博客

std::function详解-CSDN博客

std::function介绍与使用-CSDN博客

#include <iostream>
#include <vector>
#include<functional>		//函数包装模板
using namespace std;
int main()
{
	//返回类型为int ,[]为捕捉列表,用于捕捉上下文的变量供lambda函数使用,()里面为参数列表
	auto a2 = [](int a, int b)->int {
		return a + b;
	};		
	//不写->  由编译器自动推导返回类型
	auto a1 = [](int a, int b) {			
		return a + b;
	
	};
	
	cout << a1(1,2) << endl;
	cout << a2(11, 22) << endl;

	/*ambda表达式并不一定要使用auto关键字来声明。
	auto关键字可以用于推断lambda表达式的类型,使代码更简洁。但是,你也可以显式地指定lambda表达式的类型。*/
	function<double(int, int)> Add1 = [](int x, int y) -> double {
		return (x + y) / 3.0;
		};
	cout << Add1(50, 20) << endl;

	int x = 50;
    //当没有参数时,参数列表()可以省略
	auto a3 = [x] {
		return x;
	};
	cout << a3() << "\tafter x=" << x << endl;
	auto a4 = [&x] {
		x = 100;
		return x;
	};
	cout << a4() << "\tafter x=" << x << endl;
	return 0;
}

数组索引表达式:

在该文章中发现:【C++算法基础】#1基于比较的排序与桶排序 - 不要只会写冒泡了!

#include <iostream>
using namespace std;
int main()
{
	char a = "12"[0 == 0];		//"12"相当于字符数组,根据后面[]里面的布尔判断,如果0==0,为true(1)则返回"12"下标为1的元素,即2
	char b = "34"[1 == 0];	//"34"相当于字符数组,根据后面[]里面的布尔判断,如果1==0,为false(0)则返回"34"下标为0的元素,即3
	cout << a << endl;
	cout << b << endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Dear_JIANJIAN/article/details/137439794