一.概念
什么是auto:
在早期 C/C++ 中 auto 的含义是:使用 auto 修饰的变量,是具有自动存储器的局部变量 ,但遗憾的是一直没有 人去使用它,大家可思考下为什么?
C++11 中,标准委员会赋予了 auto 全新的含义即: auto 不再是一个存储类型指示符,而是作为一个新的类型 指示符来指示编译器, auto 声明的变量必须由编译器在编译时期推导而得 。
二.作用
1.可以根据右边的值去自动推导it的类型,写起来就方便了
int main()
{
const int a = 0;
int b = 0;
// 自动推到c的类型
auto c = a;
auto d = 'A';
auto e = 10.11;
// typeid打印变量的类型
cout << typeid(c).name() << endl;
cout << typeid(d).name() << endl;
cout << typeid(e).name() << endl;
// 实际中,我们不会像上面那样去用auto
// 实际中使用场景
std::map<std::string, std::string> dict = {{ "sort", "排序" }, { "insert", "插入" }
};
//std::map<std::string, std::string>::iterator it = dict.begin();
// 根据右边的值去自动推导it的类型,写起来就方便了
auto it = dict.begin();
return 0;
}
二.用于范围for -- 语法糖
int main()
{
// 语法糖 -- 范围for
int array[] = { 1, 2, 3, 4, 5 };
TestFor(array);
// C/C++ 遍历数组
for (int i = 0; i < sizeof(array) / sizeof(int); ++i)
{
cout << array[i] << endl;
}
// C++11 范围for
// 自动依次取数组array中的每个元素赋值给e
for (auto e : array)
{
cout << e << endl;
}
for (int x : array)
{
cout << x << endl;
}
// 范围for 把数组中每个值+1,e的生命周期是只有在这一个循环
for (auto& e : array)
{
e++;
}
for (auto e : array)
{
cout << e << endl;
}
return 0;
}