1.auto是什么
在C++11中,auto是用来自动推导表达式或变量的实际类型的。
#include<iostream>
using namespace std;
int main()
{
int a = 0;
auto b = a;//此时b为int 类型
cout << typeid(a).name() << endl;//typeid().name()可以自动识别变量的类型
cout << typeid(b).name() << endl;
return 0;
}
auto的原理就是根据后面的值,来推测前面的类型 。可以简化变量的初始化。
使用实例
std::vector<std::string> ve;
std::vector<std::string>::iterator it = ve.begin();
auto it = ve.begin();//替代上面
2.auto使用需要注意些什么?
注意点:
1.auto声明的变量必须初始化(auto是根据后面的值来推测这个变量的类型,如果后面没有值,自然会报错))
2.函数和模版参数不能为auto
3.不能直接声明数组
4.因为auto是一个占位符,并不是一个他自己的类型,因此不能用于类型转换或其他一些操作,如sizeof和typeid2.auto与指针和引用结合起来使用
5.用auto声明指针类型时,用auto和auto*没有任何区别,但用auto声明引用类型时则必须加&
#include<iostream>
using namespace std;
int main()
{
int x = 10;
auto a = &x;
auto* b = &x;//使用auto*时,表达式右边必须是指针,否则报错
auto& c = x;
cout << typeid(a).name() << endl;
cout << typeid(b).name() << endl;
cout << typeid(c).name() << endl;
*a = 20;
*b = 30;
c = 40;
return 0;
}
6. 在同一行定义多个变量
void TestAuto()
{
auto a = 1, b = 2;
auto c = 3, d = 4.0; // 该行代码会编译失败,因为c和d的初始化表达式类型不同
}
3.auto 与for循环
基于范围(range-based)的 for 循环 可用于遍历容器和数组
for(auto i : v)
是 C++11 引入的一种循环遍历容器的语法,其中 v
是一个容器,而 i
是容器中的元素。
实例1 遍历容器
#include <iostream>
#include <vector>
using namespace std;
int main() {
int a[] = { 1,2,3,5,2,0 };
vector<int>counts(a,a+6);
for (auto count : counts)
cout<< count<< " ";
cout << endl;
return 0;
}
//输出:1 2 3 5 2 0
实例2 遍历数组
double prices[5] = {4.99, 10.99, 6.87, 6.47, 8.88};
for (double x : prices)
std::cout << x << std::endl;