匿名函数在vc中的使用

看到js中的匿名函数,总觉得很炫,一查,这个是业界标准,php、java、c++都已经支持,连忙查下网络学习下,查到这篇写的不错,介绍了lambda expression在c++中的调用

http://www.cprogramming.com/c++11/c++11-lambda-closures.html

参考它,我写了测试代码练下。


#include "stdafx.h"

#include <iostream>

#include <string>

#include <map>

#include <algorithm>

#include <functional>

using namespace std;



void testCase1()

{

map<int, string> datas;

datas[0] = "zero";

datas[1] = "one";

datas[2] = "two";

for_each(datas.begin(), datas.end(), [](pair<int, string> pair){

cout << pair.first << "\t" << pair.second << endl;

});

}

void testCase2()

{

map<int, string> datas;

datas[0] = "zero";

datas[1] = "one";

datas[2] = "two";

for(auto pos = datas.begin(); pos != datas.end(); pos++)

{

cout << pos->first << "\t" << pos->second << endl;

}

}

void testCase3()

{

std::function<void (pair<int, string>) > output;

map<int, string> datas;

datas[0] = "zero";

datas[1] = "one";

datas[2] = "two";


/*

output = [](pair<int, string> _pair){

cout << _pair.first << "\t" << _pair.second << endl;

cout << datas.size() << endl;

};

*/

output = [&](pair<int, string> _pair){

cout << _pair.first << "\t" << _pair.second << endl;

cout << datas.size() << endl;

};

if(output)

{

for_each(datas.begin(), datas.end(), output);

}

}


int _tmain(int argc, _TCHAR* argv[])

{

string input;

testCase1();

testCase2();

testCase3();

cin>>input;


return 0;

}


你可能感兴趣的:(匿名函数在vc中的使用)