auto是什么?auto如何使用 ?auto需要注意什么?for循环?

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;

  • 5
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值