C11提供了auto这个用于类型推导的类型,它不能用于函数参数,不能用于非静态成员变量,无法定义数组和模板参数,使用auto最多的情况就是使用模板迭代器的时候

例如:

 1 // the use of auto
 2 #include <iostream>
 3 #include <map>
 4 using namespace std;
 5 
 6 int main() {
 7     map<double, double> result;
 8     result.insert(pair<double, double>(1.2, 2.2));
 9     result.insert(pair<double, double>(1.5, 2.8));
10     map<double, double>::iterator it = result.begin();
11     for(; it != result.end(); ++it) {
12         cout << it->first << "  "  << it->second << endl;
13     }   
14     // use auto
15     cout << __func__ << ",use auto ! " << endl;
16     for(auto it = result.begin(); it != result.end(); ++it) {
17         cout << it->first << "  "  << it->second << endl;
18     }   
19     return 0;
20 }

对于auto这种类型推导会不会降低效率,是不需要担心这个问题的,因为auto在编译阶段,编译器就已经帮你推倒好了变量的类型。

但是还是要慎重使用auto,因为它可能会使程序的可读性降低。

posted on 2016-04-27 12:44  LyndonYoung  阅读(632)  评论(1编辑  收藏  举报