C++11:auto关键字

一.概述

auto关键字在c++98中已经出现,在98中定义为具有自动存储器的局部变量,
c++11中标准委员会重新定义了auto关键字,表示一个类型占位符,告诉编译器,auto声明变量的类型必须由编译器在编译时期推导
而得。


注意事项:
1.auto关键字类型推断发生在编译期,程序运行时不会造成效率降低

2.auto关键字定义时就需要初始化

3.auto仅仅是一个占位符,它并不是一个真正的类型, 因此sizeof(auto)是错误的

4.auto不能作为函数的参数

5.auto不能定义数组,如auto a[3] = {1,2,3}; 错误  

 

二.使用

1.自动推导变量类型

 

	auto a = 1;
	auto b = 2LL;
	auto c = 1.0f;
	auto d = "woniu201";

	printf("%s\n", typeid(a).name());
	printf("%s\n", typeid(b).name());
	printf("%s\n", typeid(c).name());
	printf("%s\n", typeid(d).name());

 

 

2.简化代码

 

	在对一个vector容器遍历的时候,传统的方法如下:
	vector<int> v;
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		printf("%d ", *it);
	}

	使用auto关键字,简化后的方法如下:
	for (auto it = v.begin(); it != v.end(); it++)
	{
		printf("\n%d ", *it);
	}

	auto关键字的存在使得使用STL更加容易,代码更加清晰。

 

欢迎加群交流:C/C++开发交流

posted @ 2017-09-19 17:13  蜗牛201  阅读(154)  评论(0编辑  收藏  举报