在C++11中,引入了lambda,可以极大的方便了STL算法函数的处理。下面以几个算法为例:
for_each遍历算法
find_if查询算法
lower_bound排序算法
原C++:
for (std::vector<int>::itorator it(vList.begin()); it != vList.end(); it++)
{ ... }
std::vector<int>::itorator it = vList.begin();
for ( ; it != vList.end(); it++) {
if (*it > x && *it < y) break;
}
现代C++:
for_each( begin(vList), end(vList), [ ] ( int& t ) {...} );
auto it = find_if ( begin(vList), end( vList), [ = ] (int i) { return i > x && i < y; } );
下面是标准的现代C++代码:
auto comp = []( const widget& w1, const widget& w2 ) { return w1.weight() < w2.weight(); } sort( v.begin(), v.end(), comp ); auto i = lower_bound( v.begin(), v.end(), comp );