一、lambda表达式
1.1 C++98中的例子
如果要对一个数据集合进行排序,可以使用sort函数:
int main()
{
int array[] = {
4,1,8,5,3,7,0,9,2,6 };
// 默认按照小于比较,排出来结果是升序
std::sort(array, array + sizeof(array) / sizeof(array[0]));
// 如果需要降序,需要改变元素的比较规则
std::sort(array, array + sizeof(array) / sizeof(array[0]), greater<int>());
return 0;
}
升序:
降序:
如果元素是自定义类型,那么要通过仿函数来确定比较规则:
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(