中国开发网: 论坛: 程序员情感CBD: 贴子 700583
龙之吻
lambdas and auto
Earlier, I mentioned storing lambdas in tr1::functions. But you shouldn't do that unless it's necessary, as tr1::function has some overhead. If you want to reuse a lambda, or simply want to give it a name, you can use auto. Here's an example, which also does something neat:



C:\Temp>type autolambdakitty.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;



template <typename T, typename Predicate> void keep_if(vector<T>& v, Predicate pred) {

auto notpred = [&](const T& t) {

return !pred(t);

};



v.erase(remove_if(v.begin(), v.end(), notpred), v.end());

}



template <typename Container> void print(const Container& c) {

for_each(c.begin(), c.end(), [](const typename Container::value_type& e) { cout << e << " "; });

cout << endl;

}



int main() {

vector<int> a;



for (int i = 0; i < 100; ++i) {

a.push_back(i);

}



vector<int> b;



for (int i = 100; i < 200; ++i) {

b.push_back(i);

}



auto prime = [](const int n) -> bool {

if (n < 2) {

return false;

}



for (int i = 2; i <= n / i; ++i) {

if (n % i == 0) {

return false;

}

}



return true;

};



keep_if(a, prime);

keep_if(b, prime);



print(a);

print(b);

}



C:\Temp>cl /EHsc /nologo /W4 autolambdakitty.cpp

autolambdakitty.cpp



C:\Temp>autolambdakitty

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199



notpred is a negator lambda! Note that we can't use C++98 <functional>'s not1(), as that requires your predicate to derive from unary_function, and lambdas don't.


机器人,这首歌学会了没有?

我们的目标是->没有蛀牙!

相关信息:


欢迎光临本社区,您还没有登录,不能发贴子。请在 这里登录