1. 程式人生 > >c++ 11 陣列 和lambda表示式 語法 / 函式包裝器 基本用法

c++ 11 陣列 和lambda表示式 語法 / 函式包裝器 基本用法


//倒敘遍歷陣列並輸出 

// []裡面的變數可以當做返回值來理解 (int x) 這裡就是每次迭代器的值,也就是陣列的元素的值

void main()
{
	array<int, 5> arr = { 1,2,3,4,5 };
	int a = 0;
	std::for_each(arr.rbegin(), arr.rend(), [&a](int x) { a = x; cout << a; });
	system("pause");
}


///lambda表示式遍歷二維陣列

void main()
{
	array<int, 5> arr = { 1,2,3,4,5 };
	array<array<int, 5>, 3> arr1 = { arr,arr,arr };
	int a = 0;
	std::for_each(arr1.rbegin(), arr1.rend(), [&a](array<int, 5> arr2)  
	{
		for_each(arr2.rbegin(), arr2.rend(), [](int x) {cout << x << endl; }); //如果實現累加[&a] a+=x即可
	}
	);
	system("pause");
}


函式包裝器基本用法
template<typename T, typename F>

T run(T a, T b, F f)
{
	return f(a, b);
}


 
int test(int a, int b)
{
	return a + b;
}

double test1(double a, double b)
{
	return a + b;
}
 
std::function<int(int, int)> func;
std::function<double(double, double)> func1;
void main()
{
	func = test;
	func1 = test1;
	cout << run(1, 2, func) << endl;
	cout << run(1.2, 2.0, func1)<<endl;
	cout << run(1, 2, test) << endl;
	cout << run(1.2, 2.0, test1);
	system("pause");
}