auto关键字 与 基于范围的for循环

随着程序越来越复杂,程序中用到的类型也越来越复杂,经常体现在:

    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,所以上面都是我的理解+搬运的 :rofl:

觉得全面的点个赞吧

@jhxs1182 从哪里搬运来的?

保密

我也顺便学了学

@jhxs1182 快点说!

https://blog.csdn.net/qq_42251157/article/details/130783028?ops_request_misc=%257B%2522request%255Fid%2522%253A%25222c850cadef28b6ec979a1a1c231aa30e%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=2c850cadef28b6ec979a1a1c231aa30e&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~baidu_landing_v2~default-1-130783028-null-null.142^v101^pc_search_result_base9&utm_term=c%2B%2B%20for%28%3A%29&spm=1018.2226.3001.4187

说了

补充一点
for(auto count : counts)是C++11中的语法,即:Range-based for loop。

其中counts应满足:begin(counts), end(counts)是合法的。

其等价于for(some_iterator p = begin(counts); p != end(counts); ++p)且some_type count = *p。

另外还可以是for(auto& count : counts), for(auto&& count: counts)。

它们的区别在于count是值还是引用(左值引用或右值引用)。

在c++14中还允许for(count : counts),等价于for(auto&& count: counts)。

生日快乐