一、lambda表达式
1)、为啥需要引入lambda?
在c++98中,我们使用sort对一段自定义类型进行排序的时候,每次都需要传一个仿函数,即手写一个完整的类。甚至有时需要同时实现排升序和降序,就需要各自手写一个类,非常不方便!所以C++11引入了lambda表达式!
lamaba是一个匿名函数对象,是一个可调用对象,表达式本质上也是一个类(vs中类名为lambda_uuid),并实现了operator()。
【C98玩法】:
struct Goods
{
string _name; // 名字
double _price; // 价格
int _evaluate; // 评价
Goods(const char* str, double price, int evaluate)
:_name(str)
, _price(price)
, _evaluate(evaluate)
{
}
};
struct ComparePriceLess
{
bool operator()(const Goods& gl, const Goods& gr)
{
return gl._price < gr._price;
}
};
struct ComparePriceGreater
{
bool operator()(const Goods& gl, const Goods& gr)
{
return gl._price > gr._price;
}
};
int main()
{
vector<Goods> v = {
{
"苹果", 2.1, 5 }, {
"香蕉", 3, 4 },
{
"橙子", 2.2, 3 }, {
"菠萝", 1.5, 4 } };
sort(v.begin(), v.end(), ComparePriceLess());
sort(v.begin(), v.end(), ComparePriceGreater());
}
【C++11 lambda表达式】:
int main()
{
vector<Goods> v = {
{
"苹果", 2.1, 5 }, {
"香蕉", 3, 4 },
{
"橙子", 2.2, 3 }, {
"菠萝", 1.5, 4 } };
sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
return g1._price < g2._price; });
sort(v.begin(), v.end(), [](const Goods& g1, const Goods