struct Goods
{
string _name; // 名字
double _price; // 价格
int _evaluate; // 评价
Goods(const char* str, double price, int evaluate)
:_name(str)
, _price(price)
, _evaluate(evaluate)
{}
};
//struct ComparePriceLess
struct Compare1
{
bool operator()(const Goods& gl, const Goods& gr)
{
return gl._price < gr._price;
}
};
//struct ComparePriceGreater
struct Compare2
{
bool operator()(const Goods& gl, const Goods& gr)
{
return gl._price > gr._price;
}
};
struct CompareEvaluateGreater
{
bool operator()(const Goods& gl, const Goods& gr)
{
return gl._evaluate > gr._evaluate;
}
};
int main()
{
vector<Goods> v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2, 3 }, { "菠萝", 1.5, 4 } };
//sort(v.begin(), v.end(), Compare1()); // 价格升序
//sort(v.begin(), v.end(), Compare2()); // 价格降序
//sort(v.begin(), v.end(), CompareEvaluateGreater()); // 评价的降序
sort(v.begin(), v.end(), Compare1());
sort(v.begin(), v.end(), Compare2());
return 0;
}
为什么要引入lambda?
[捕捉列表] (参数列表) mutable -> 返回值类型 { 函数体 }
//[捕捉列表] (参数列表) mutable -> 返回值类型 { 函数体 }
// 局部的匿名函数对象
auto less = [](int x, int y)->bool {return x < y; };
cout << less(1, 2) << endl;
int main()
{
vector<Goods> v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2, 3 }, { "菠萝", 1.5, 4 } };
sort(v.begin(), v.end(), Compare1());
sort(v.begin(), v.end(), Compare2());
//auto goodsPriceLess = [](const Goods& x, const Goods& y)->bool {return x._price < y._price; };
// 没有返回值时此部分可省略
auto goodsPriceLess = [](const Goods& x, const Goods& y){return x._price < y._price; };
cout << goodsPriceLess(v[0], v[1]) << endl;
sort(v.begin(), v.end(), goodsPriceLess);
sort(v.begin(), v.end(), [](const Goods& x, const Goods& y) {
return x._price < y._price; });
sort(v.begin(), v.end(), [](const Goods& x, const Goods& y) {
return x._price > y._price;});
sort(v.begin(), v.end(), [](const Goods& x, const Goods& y) {
return x._evaluate < y._evaluate;});
sort(v.begin(), v.end(), [](const Goods& x, const Goods& y) {
return x._evaluate > y._evaluate;});
return 0;
}