小试lambda

长平狐 发布于 2013/01/11 10:33
阅读 23
收藏 0


写个小程序小试下lambda的使用,是很方便啊!

#include <iostream>
#include <vector>
#include <stdlib.h>
#include <algorithm>
using namespace std;

int main(int argc, char *argv[])
{
	vector<int> v;
	v.reserve(100);
	for(int i=0; i<10; ++i)
		v.push_back(random()%10);
	cout<<"vector: ";
	auto f = [](int n){cout<<" "<<n;};
	for_each(v.begin(), v.end(), f);
	cout<<endl;


	cout<<"sort vector: ";
	auto s = [](int l, int r) {return l<r;};
	sort(v.begin(), v.end(), s);
	for_each(v.begin(), v.end(), f);
	cout<<endl;
	return 0;
}

编译:g++ -std=c++0x main.cpp

运行:./a.out

结果输出:

vector:  3 6 7 5 3 5 6 2 9 1
sort vector:  1 2 3 3 5 5 6 6 7 9



原文链接:http://blog.csdn.net/fjb2080/article/details/7470524
加载中
返回顶部
顶部