您的位置:首页 > 编程语言 > C语言/C++

STL--Lambdas(二)

2016-06-05 00:00 357 查看
摘要: Using Lambdas

The benefit of Lambdas

Using lambdas to specify behavior inside the STL framework solves a lot of drawbacks of previous attempts.

Suppose that you search in a collection for the first element with a value that is between x and y:

[code=language-cpp]#include <algorithm>
#include <deque>
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
deque<int> coll = { 1, 3, 19, 5, 13, 7, 11, 2, 17 };

int x = 5;
int y = 12;

auto pos = find_if(coll.begin(), coll.end(),    //range
[=](int i) {                 //search criterion
return i > x && i < y;
});
cout << "first elem >5 and <12: " << *pos << endl;

system("pause");
}

/*
* output of program:
*
* first elem >5 and <12: 7
*
*/


Using Lambdas as Sorting Criterion

[code=language-cpp]#include <algorithm>
#include <deque>
#include <string>
#include <iostream>
using namespace std;

class Person {
public:
string firstname() const;
string lastname() const;
...
};

int main()
{
deque<Perosn> coll;
...
//sort Perosn according to lastname(and firstname):
sort(coll.begin(), coll.end(),                    //range
[] (const Person& p1, const Person& p2){     //sort criterion
return p1.lastname()<p2.lastname() ||
(p1.lastname()==p2.lastname() &&
p1.firstname()<p2.firstname());
});
...
}


STL--Lambdas(一) http://my.oschina.net/daowuming/blog/687290
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ STL Lambdas