C++11 example of using the auto keyword

  • 2020-06-12 10:13:28
  • OfStack

1. An overview of the

The auto keyword appears in c++98, where it is defined as a local variable with automatic memory,

In c++11, the Standards Committee redefined the auto keyword to represent a type placeholder, telling the compiler that the type of a variable declared by auto must be derived by the compiler at compile time
.

Notes:

1.auto keyword type inference occurs at compile time and does not cause a reduction in efficiency when the program is run

2.auto keyword definition needs to be initialized

3.auto is just a placeholder, it is not a true type, so sizeof(auto) is incorrect

4.auto cannot be used as an argument to a function

5.auto cannot define an array, such as auto a[3] = {1,2,3}; error

2. Use

1. Automatic derivation of variable types


 auto a = 1;
 auto b = 2LL;
 auto c = 1.0f;
 auto d = "woniu201";
 printf("%s\n", typeid(a).name());
 printf("%s\n", typeid(b).name());
 printf("%s\n", typeid(c).name());
 printf("%s\n", typeid(d).name());

Simplify the code


 // In the 1 a vector The traditional approach to container traversal is as follows :
 vector<int> v;
 for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
 {
 printf("%d ", *it);
 }
 // use auto Keyword, the simplified method is as follows :
 for (auto it = v.begin(); it != v.end(); it++)
 {
 printf("\n%d ", *it);
 }
 //auto The presence of a keyword makes it useful STL Easier, clearer code. 

conclusion


Related articles: