VC10和C++ 0x (2) - auto

auto这个关键字来自C++ 98标准。在C++ 98中它没有什么作用,C++ 0x中“借用”它来作为自动类型推演(automatic type deduction)。当auto出现在声明中时,它表示“请用初始化我的表达式类型作为我的类型”。例如下面代码:

 

C:/Temp>type autocat.cpp

#include

#include

#include

#include

#include

using namespace std;

using namespace std::tr1;

int main() {

    map m;

const regex r("(//w +) (//w+) ");

    for (string s; getline(cin, s); ) {

        smatch results;

        if (regex_match(s, results, r)) {

            m[results[1]] = results[2];

        }

    }

    for (auto i = m.begin(); i != m.end(); ++i) {

        cout << i->second << " are " << i->first << endl;

    }

}

 

运行结果:

cute kittens

ugly puppies

evil goblins

^Z

kittens are cute

goblins are evil

puppies are ugly

 

上面例子中i的类型在编译时推演为 map::iterator, 有了auto关键字你再也不用写又长又烦的代码了。

(注意 m.begin() 返回类型是 iterator, 而不是 const_iterator, 因为这里的m并不是const.  C++0x 中的cbegin() 能够解决这个问题,它返回non-const容器的const迭代器.)

 

lambda表达式和auto

前面的文章中提到了用tr1::functions来存储lambda表达式。 但是不建议那样做除非不得已,因为tr1::functions的开销问题。

 

如果你需要复用lambda表达式或者像给它命名,那么auto是更好的选择。

C:/Temp>type autolambdakitty.cpp

#include

#include

#include

#include

using namespace std;

template void keep_if(vector& v, Predicate pred) {

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

        return !pred(t);

    };

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

}

template void print(const Container& c) {

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

    cout << endl;

}

int main() {

    vector a;

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

        a.push_back(i);

    }

    vector 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);

}

 

运行结果:

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是一个lambda表达式的否定式。这个例子中我们不能够使用C++ 98的not1(),因为not1要求你的谓词是从unary_function派生的,但是lambda并不要求这点,所以很多情况下使用lambda更灵活。  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bruce Jia(上海)

熬夜码字换酒钱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值