找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 3584|回复: 0

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

[复制链接]
发表于 2012-2-22 15:37:36 | 显示全部楼层 |阅读模式
auto这个关键字来自C++ 98标准。在C++ 98中它没有什么作用,C++ 0x中“借用”它来作为自动类型推演(automatic type deduction)。当auto出现在声明中时,它表示“请用初始化我的表达式类型作为我的类型”。例如下面代码: C:\Temp>type autocat.cpp
1 #include <iostream>
2
3 #include <map>
4
5 #include <ostream>
6
7 #include <regex>
8
9 #include <string>
10
11 using namespace std;
12
13 using namespace std::tr1;
14
15 int main() {
16
17     map<string, string> m;
18
19 const regex r("(\\w+) (\\w+)");
20
21     for (string s; getline(cin, s); ) {
22
23         smatch results;
24
25         if (regex_match(s, results, r)) {
26
27             m[results[1]] = results[2];
28
29         }
30
31     }
32
33     for (auto i = m.begin(); i != m.end(); ++i) {
34
35         cout << i->second << " are " << i->first << endl;
36
37     }
38
39 }
复制代码

40  运行结果:cute kittensugly puppiesevil goblins^Zkittens are cutegoblins are evilpuppies are ugly 上面例子中i的类型在编译时推演为 map<string, string>::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
  1. #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);}
复制代码
运行结果:2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97101 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更灵活。  

您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-5-1 02:27 , Processed in 0.010923 second(s), 5 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表