随着程序越来越复杂,程序中用到的类型也越来越复杂,经常体现在:
1.类型难以拼写
2.含义不明确导致容易出错
#include <string>
#include <map>
int main()
{
std::map<std::string, std::string> m{ { "apple", "苹果" }, { "orange", "橙子" },
{"pear","梨"} };
std::map<std::string, std::string>::iterator it = m.begin();
while (it != m.end())
{
//....
}
return 0;
}
std::mapstd::string,std::string::iterator 是一个类型,但是该类型太长了,特别容易写错,聪明的同学可能已经想到:可以通过typedef给类型取别名,比如:
#include <string>
#include <map>
typedef std::map<std::string, std::string> Map;
int main()
{
Map m{ { "apple", "苹果" },{ "orange", "橙子" }, {"pear","梨"} };
Map::iterator it = m.begin();
while (it != m.end())
{
//....
}
return 0;
}
使用typedef给类型取别名确实可以简化代码,但是typedef有时会遇到新的难题:
typedef char* pstring;
int main()
{
const pstring p1; // 编译成功还是失败?
const pstring* p2; // 编译成功还是失败?
return 0;
}
当运行以上代码时,会报错
但是,auto不需要自己去考虑这个变量的类型,而是把这件事情交给了编译器来进行,回到开头的那段代码:
#include <string>
#include <map>
int main()
{
std::map<std::string, std::string> m{ { "apple", "苹果" }, { "orange", "橙子" },
{"pear","梨"} };
auto it = m.begin();
while (it != m.end())
{
//....
}
return 0;
}
auto替代了类型 std::mapstd::string,std::string::iterator ,是不是就特别方便。
int TestAuto()
{
return 10;
}
int main()
{
int a = 10;
auto b = a;
auto c = 'a';
auto d = TestAuto();
cout << typeid(b).name() << endl;
cout << typeid(c).name() << endl;
cout << typeid(d).name() << endl;
//auto e; 无法通过编译,使用auto定义变量时必须对其进行初始化
return 0;
}
用auto声明指针类型时,用auto和auto*没有任何区别,但用auto声明引用类型时则必须加&
#include<iostream>
using namespace std;
int main()
{
auto a = 3;
auto pa1 = &a;
auto* pa2 = &a;
auto& b = a;
cout << typeid(a).name() << endl;
cout << typeid(pa1).name() << endl;
cout << typeid(pa2).name() << endl;
cout << typeid(b).name() << endl;
return 0;
}
重点!!!!!!!
1.auto不能作为函数的参数
2.auto不能直接用来声明数组
3.auto在实际中最常见的优势用法就是跟新式for循环还有lambda表达式等进行配合使用
在C++98中如果要遍历一个数组,可以按照以下方式进行(我以前的c++不会开c++14,所以以前一直在用98):
void TestFor()
{
int array[] = { 1, 2, 3, 4, 5 };
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
array[i] *= 2;
for (int* p = array; p < array + sizeof(array)/ sizeof(array[0]); ++p)
cout << *p << endl;
}
对于一个有范围的集合 而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此C++11中 引入了基于范围的for循环。for循环后的括号由冒号“ :”分为两部分:第一部分是范围内用于迭代的变量, 第二部分则表示被迭代的范围 。
void TestFor()
{
int a[] = { 1, 2, 3, 4, 5 };
for (auto& e : a)
e *= 2;
for (auto e : a)
cout << e << " ";
return;
}
int main()
{
TestFor();
return 0;
}
注:与普通循环类似,可以用continue来结束本次循环,也可以用break来跳出整个循环。
彩蛋:我因为不了解auto,所以上面都是我的理解+搬运的