话说新标准出来也蛮久的了, 是时候跟进了, 先试试lamba, 还满好玩。
先看看不用lamba, 用仿函数的代码如何:
class Acc // functor { public: Acc(int & Uppercase): Uppercase_(Uppercase){} void operator()(char c) const { if (isupper(c)){ Uppercase_++; } } private: int & Uppercase_; }; void lamba_Test() { char s[] = "Hello World!"; int Uppercase = 0; for_each(s, s + sizeof(s), Acc(Uppercase)); // use functor cout << Uppercase << " uppercase letters in: " << s << endl; }
再看看用lamba之后:
void lamba_Test() // lamba expersion { char s[] = "Hello World!"; int Uppercase = 0; //modified by the lambda for_each(s, s + sizeof(s), [&Uppercase](char c) { // or try auto c if (isupper(c)) Uppercase++;} ); cout << Uppercase << " uppercase letters in: " << s << endl; }
打字少多了,看代码不用上窜下跳了, 爽爆了有木有!
时间: 2024-10-11 05:31:10