可以根据右边a值的类型自动推导左边值的类型
int a = 0;
//int b = a;
auto b = a;
auto c = &a;
auto& d = a;
typeid可以拿到类型
int a = 0;
//int b = a;
auto b = a;
auto c = &a;
auto& d = a;
cout << typeid(c).name() << endl;
cout << typeid(d).name() << endl;
cout << typeid(it).name() << endl;
普通场景没有什么价值
类型很长,就有价值,简化代码
std::vector<std::string> v;
//std::vector::iterator it = v.begin();
auto it = v.begin();
当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对第一个类型进行推导,然后用推导出来的类型定义其他变量。
void TestAuto()
{
auto a = 1, b = 2;
auto c = 3, d = 4.0; // 该行代码会编译失败,因为c和d的初始化表达式类型不同
}
auto不能推导的场景
void Test(auto a)//编译器无法对a的实际类型进行推导,编译失败
int a[] = {1,2,3};
auto b[] = {4,5,6};//错误
int main()
{
int array[] = { 1, 2, 3, 4, 5 };
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
array[i] *= 2;
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
cout << array[i] << " ";
cout << endl;
// 范围for
// 依次取数组中的数据赋值给i
// 自动判断结束
// 自动迭代
for (auto i : array)
{
cout << i << " ";
}
cout << endl;
return 0;
}
用int也可以,但是auto可以应对数组的类型变化。所以范围for都会结合auto用。
for (auto& x : array)
{
x *= 2;
}
要改变数组中数据的时候加引用,不能用指针,依次取数组中的数据赋值给x,如果x是指针,类型不匹配
错误使用情况:
void TestFor(int array[])
{
for (auto& e : array)
cout << e << endl;
}
要的是数组名,不是指针,所以上面的代码是错误的