auto的作用
1. 声明自动类型的变量,根据被赋值的类型自动推导变量的类型
#include <iostream>
using namespace std;
int main() {
int x;
auto y = 12.3; //y被自动推导为double
cout << sizeof(x) << endl; //4
cout << sizeof(y) << endl; //8
return 0;
}
auto
关键字在C语言中就已经存在了,只不过在C语言中它的作用是声明自动变量:
auto int z = 123;
z
本来是局部变量,加上 auto
后变成了局部的自动变量,就是当前变量的生存周期是由编译器自动决定的,但是这和局部变量没有区别,所以 auto
在 C语言中并没有发挥什么作用。
2. 简化代码
容器,是封装好的数据结构。C++ 中的 vector
、map
和 queue
等都是容器,通常涉及到的一个操作是遍历容器。遍历容器的工具类型是迭代器,不同容器的迭代器类型是不同的。
#include <iostream>
#include <map>
using namespace std;
int main() {
int x;
//1.声明自动类型变量,实际类型由编译器自动推导
auto y = 12.3; //y被自动推导为double
int z = 123; //z本来是局部变量,加上auto成为局部自动变量
//2.遍历元素
map<int, int> arr;
for (int i = 0; i < 10; i++) {
arr[rand() % 100] = rand();
}
//遍历整型到整型的map类型的迭代器类型:map<int, int>::iterator,iter是迭代器变量
//map存数据的类型本质上是pair类型,第一项是key,第二项value
//map<int, int>::iterator iter = arr.begin();
//等价于:
auto iter = arr.begin(); //iter由arr.begin()返回值来决定
while (iter != arr.end()) {
//查看当前这项的key和value
cout << iter->first << " " << iter->second << endl;
iter++;
}
cout << sizeof(x) << endl;
cout << sizeof(y) << endl;
return 0;
}
auto
变量的类型只根据赋值来确定,auto
是 编译器 的功能,因为编译时要确定变量的类型和所占的空间。
C++ 中 for 的新语法:
map<int, int> arr;
for (int i = 0; i < 10; i++) {
arr[rand() % 100] = rand();
}
for (auto x : arr) {
cout << x.first << " " << x.second << endl;
}
//等价于:
/**
for (pari<int, int> x : arr) {
cout << x.first << " " << x.second << endl;
}
**/
获取auto推导出来的类型
如何确定 auto
关键字推导出来的类型?
- 使用
typeid
会返回类型信息对象。
int x;
//1.声明自动类型变量,实际类型由编译器自动推导
auto y = 12.3; //y被自动推导为double
int z = 123; //z本来是局部变量,加上auto成为局部自动变量
const type_info &xt = typeid(x);
//typeid返回类型对象信息,name()结果是类型缩写
cout << typeid(x).name() << endl; //i
cout << typeid(y).name() << endl; //d
cout << typeid(z).name() << endl; //i
hash_code
函数通常用来判断两个类型是否相同:每种类型的hashcode不同,可以通过hashcode判断类型
int x;
//1.声明自动类型变量,实际类型由编译器自动推导
auto y = 12.3; //y被自动推导为double
int z = 123; //z本来是局部变量,加上auto成为局部自动变量
//每种类型的hashcode不同,可以通过hashcode判断类型
if (typeid(y).hash_code() == typeid(float).hash_code()) {
cout << "float type" << endl;
}
if (typeid(y).hash_code() == typeid(double).hash_code()) {
cout << "double type" << endl;
}
auto的限制
1、不能作为函数参数
void func(auto x, auto y) {}
void func(auto x, double y) {}
int main() {
func(1, 2);
func(1.2, 1.2);
return 0;
}
编译报错,影响重载形式下的调用绑定。
2、C++11中的限制,无法作为模板参数
3、无法定义数组
auto w[100] = {123, 456, 678}; //编译报错
4、不能用于定义非静态成员变量
class Base {
public :
static int x;
};
auto Base::x = 123;
对象属性不能用 auto
关键字定义:
class Base {
public :
auto y; //编译报错
}