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();
}