C++11/14 lamba, 仿函数 对比

C++11

C++14

 

话说新标准出来也蛮久的了, 是时候跟进了, 先试试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;
}
复制代码

 

打字少多了,看代码不用上窜下跳了,  爽爆了有木有!

你可能感兴趣的:(C++11/14 lamba, 仿函数 对比)