标签:c++11
在C++11之前,auto关键字用来指定存储期。在新标准中,它的功能变为类型推断。auto现在成了一个类型的占位符,通知编译器去根据初始化代码推断所声明变量的真实类型。各种作用域内声明变量都可以用到它。例如,名空间中,程序块中,或是for循环的初始化语句中。
auto i = 42; // i is an int auto p = new char; // p is a char *使用auto通常意味着更短的代码(除非你所用类型是int,它会比auto少一个字母)。试想一下当你遍历STL容器时需要声明的那些迭代器(iterator)。现在不需要去声明那些typedef就可以得到简洁的代码了。
map<int, vector<int>> map; for (auto it = begin(map); it != end(map); ++it) { }
int* p1 = NULL; int* p2 = nullptr; if (p1 == p2) { cout << "p1 == p2" << endl; }
<span style="white-space:pre"> </span>bool f = nullptr;
重新执行结果:
<span style="font-family: 'Microsoft YaHei', 宋体, 'Myriad Pro', Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif;">p1 == p2</span>
<pre name="code" class="plain">请按任意键继续. . .
为了在遍历容器时支持”foreach”用法,C++11扩展了for语句的语法。用这个新的写法,可以遍历C类型的数组、初始化列表以及任何重载了非成员的begin()和end()函数的类型。
如果你只是想对集合或数组的每个元素做一些操作,而不关心下标、迭代器位置或者元素个数,那么这种foreach的for循环将会非常有用。
map<string , vector<int>> mapForLoop; vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); mapForLoop["one"] = vec; for (const auto& kvp : mapForLoop) { cout << kvp.first << endl; for (auto vec : kvp.second) { cout << vec << endl; } } int arr[] = { 1, 2, 3, 4, 5 }; for (int& e : arr) { e = e * e; } for (int& e : arr) { cout << e << endl; }重新执行结果:
one 1 2 3 1 4 9 16 25 请按任意键继续. . .
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:c++11
原文地址:http://blog.csdn.net/yamingwu/article/details/45787765