auto关键字

auto在替换长类型时使用,或者不想用using或typedef来创建别名时使用。

例子1:auto自动确定变量类型

#include <iostream>
#include <string>

int main()
{
	auto a = 5;
	auto c = 5L;
	auto d = 5.5f;
	auto e = "007";
	auto f = nullptr;
	auto b = a;
	std::cin.get();
}

例子2:auto自动识别返回值的类型

#include <iostream>
#include <string>
#include <vector>

std::string GetName()
{
	return"007";
}

int main()
{
	auto name = GetName();  //std::string name = GetName();
	int a = name.size();  //如果std::string GetName() 改成char* GetName()就不行了,因为size()用于string
	std::cin.get();
}

例子3:类型太长,使用auto

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>

class Device {};

class DeviceManager
{
private:
	std::unordered_map<std::string, std::vector<Device*>> m_Devices;  //有一个从string到vector<Device*>的map映射,变量名m_Devices
public:
	const std::unordered_map<std::string, std::vector<Device*>>& GetDevices() const
	{
		return m_Devices;
	}
};

int main()
{
	std::vector<std::string> strings;
	strings.push_back("Apple");
	strings.push_back("Orange");
	//for (std::vector<std::string>::iterator it = strings.begin();it != strings.end(); it++) 原来的状态,iterator是迭代器
	for (auto it = strings.begin(); it != strings.end(); it++)
	{
		std::cout << *it << std::endl;
	}

    //不使用auto,要写的是//后面的
	//using DeviceMap = std::unordered_map<std::string, std::vector<Device*>>;
	//typedef std::unordered_map<std::string, std::vector<Device*>> DeviceMap;
	DeviceManager dm;
	//const DeviceMap&  devices = dm.GetDevices();
	const auto& devices = dm.GetDevices();
	std::cin.get();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值