一、lamda表达式
lamda表达式表述
表达式类型
- [capture list] (params list) -> return type {function body}
- [capture list] (params list) {function body}
- [capture list] {function body}
bool cmp(int a, int b)
{
return a < b;
}
sort(myvec.begin(), myvec.end(), cmp); // 旧式做法
sort(lbvec.begin(), lbvec.end(), [](int a, int b) -> bool { return a < b; }); // Lambda表达式
/*
注:sort中的function返回一个bool值,这个bool值指示是否应该将传递进的第一个参数放到第二个参数前面
sort默认使用less<int>(),即升序
*/
二、Compare Type
build custom comparator
compare Type使用场景常见于要构造STL中的有序对象时,如priority_queue,但是其中存储的元素为用户自定义类型,因此无法使用标准的greater<>, less<>模板,解决方法如下
// using lambda to compare elements.
auto compare = [](int lhs, int rhs)
{
return lhs < rhs;
};
std::priority_queue<int, std::vector<int>, decltype(compare)> q(compare);
//struct
struct CustomCompare
{
bool operator()(const int& lhs, const int& rhs)
{
return lhs < rhs;
}
};
priority_queue<int,vector<int>, CustomCompare > pq;
三、value_type
这种c++很多特性都是因为要使用template进行泛型编程,value_type就是用来确定一个容器中的元素的属性
template<typename Container>
typename Container::value_type sum(const Container& cont)
{
typename Container::value_type total = 0;
for (const auto& e : cont)
total += e;
return total;
}