匿名函数在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;

}


转载于:https://my.oschina.net/u/2318770/blog/383749

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值