auto specifier

auto specifier

auto这个关键字是由c++11引进的,使用auto,我们可以声明变量而无需指定其类型,其类型由初始化的数据进行推断。

1
2
3
4
5
6
7
8
// type int
auto var_1 = 5;

// type char
auto var_2 = 'C';

std::cout<<var_1<<std::endl;
std::cout<<var_2<<std::endl;

我们也可以记录一些其他的类型,例如函数或者迭代器,以下就是将一个lambda函数存放在auto:

1
2
3
4
5
auto fun_sum = [](int a , int b){
return a+b;
};

std::cout<<fun_sum(4,5)<<std::endl;

auto的最大优点就是,我们不需要书写很长的变量类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::map<std::string, std::string> mapOfStrs;

// Insert data in Map
mapOfStrs.insert(std::pair<std::string, std::string>("first", "1") );
mapOfStrs.insert(std::pair<std::string, std::string>("sec", "2") );
mapOfStrs.insert(std::pair<std::string, std::string>("thirs", "3") );

//std::map<std::string, std::string>::iterator it = mapOfStrs.begin();
auto it = mapOfStrs.begin();
while(it != mapOfStrs.end())
{
std::cout<<it->first<<"::"<<it->second<<std::endl;
it++;
}

Important points about auto variable in C++11

  1. 初始化auto变量后,您可以更改值,但不能更改类型
  2. 不能只声明而不进行初始化

Returning an auto from a function

要从函数返回auto变量,我们可以以特殊方式声明它

1
2
3
4
5
6
auto sum(int x, int y) -> int
{
return x + y;
}

auto value = sum(3, 5);