C++ 11 实用的新特性

C++ 11 实用的新特性

无意间看到了这篇文章,发现C++11新增的特性对我来说太友善了,特此记录一下
文章链接C++开发者都应该使用的10个C++11特性
这里特点强调一下两个特性


1.auto类型

在C++11之前,auto关键字用来指定存储期。在新标准中,它的功能变为类型推断。auto现在成了一个类型的占位符,通知编译器去根据初始化代码推断所声明变量的真实类型。各种作用域内声明变量都可以用到它。例如,名空间中,程序块中,或是for循环的初始化语句中。

auto i = 42;        // i is an int

auto l = 42LL;      // l is an long long

auto p = new
foo(); // p is a foo*

auto的作用主要是用来遍历各种容器,比如遍历map

std::map<std::string, std::vector<int>> map;
for(auto it = begin(map); it != end(map); ++it)
{}

2.Range-based for loops (基于范围的for循环)

为了在遍历容器时支持”foreach”用法,C++11扩展了for语句的语法。用这个新的写法,可以遍历C类型的数组、初始化列表以及任何重载了非成员的begin()和end()函数的类型。

如果你只是想对集合或数组的每个元素做一些操作,而不关心下标、迭代器位置或者元素个数,那么这种foreach的for循环将会非常有用。

std::map<std::string, std::vector<int>> map;
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
map["one"] = v;
for(const auto& kvp : map)
{
  std::cout << kvp.first << std::endl;
  for(auto v : kvp.second)
  {
   std::cout << v << std::endl;
  }
}
int arr[] = {1,2,3,4,5};
for(int& e : arr)
{
  e = e*e;
}

特别是auto类型和foreach一起用的时候,有奇效

#include<iostream>
#include<map>
using namespace std;
int main()
{
  map<int,char> mp;
  mp[1] = 'a';
  mp[2] = 'b';
  mp[4] = 'd';
  mp[3] = 'c';
  for(auto it:mp)
  {
    cout << it.second << endl;  //非常简便的遍历map的方式
  }
}
... ... ...