测试lambda的使用

// testLambda.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <algorithm>
#include <vector>
#include <iostream>
#include <functional>//使用std::function必须包含这个头文件

using namespace std;

/*
Title:测试lambda的使用
Date:2014-09-18
Environment:[1]VS2013Update2
*/

class CTestLambda
{
public:
	void SetFunction(std::function<int(int, int)> f)
	{
		m_func = f;

	}
	std::function<int(int, int)> m_func;
};

void testCase1()
{
	std::cout << "测试 lambda函数类型变量 赋值, 传递" << std::endl;
	//Method1
	auto f1 = [](int x, int y)->int{
		return x + y;
	};

	CTestLambda tl;
	tl.SetFunction(f1);

	cout << "3+2=" << tl.m_func(3, 2) << endl;

	//Method2,reassign function attribute
	std::function<int(int, int)> f2 = [](int x, int y)->int{
		return x*y;
	};
	tl.SetFunction(f2);
	cout << "3*2=" << tl.m_func(3, 2) << endl;
}

void testCase2()
{
	std::cout << "测试:standard generic algorithm 中的使用" << std::endl;

	vector<int> vecN;
	vecN.push_back(2);
	vecN.push_back(3);

	vector<int> vecResult(2);

	std::transform(vecN.begin(), vecN.end(), 
		vecResult.begin(), [](int n)->int{ return n*n; });

	std::for_each(vecResult.begin(), vecResult.end(), [](int n){
		std::cout << n << endl;
	});	
}

void testCase3()
{
	std::cout << "测试:捕获外部变量" << std::endl;
	std::string str = "我在外面!";
	[=](){
		std::cout << "[=]捕获所有外部变量!" << str.c_str() << std::endl;
	}();
	[str](){
		std::cout << "[str]捕获str变量(只读)!" << str.c_str() << std::endl;
	}();
	[&str](){
		str = "i changed it!";
		std::cout << "[&str]捕获str变量并改变它的值,如果有多个variable中间用comma symbol separate!" << str.c_str() << std::endl;
	}();
}

int _tmain(int argc, _TCHAR* argv[])
{
	testCase1();
	testCase2();
	testCase3();

	cin.get();

	return 0;
}

你可能感兴趣的:(测试lambda的使用)