New features of C++11 (6) - auto type modifier

Features


C++11 provides an auto type modifier, which can automatically determine the type of the variable according to the content of the initialization code, rather than specifying it explicitly. E.g:


auto a1 = 123;

auto a2 = '2';


Since the type of 123 is int, the type of a1 is int. In the same way, the type of '2' is char, so the type of a2 is also char.


Of course, if you just use auto instead of int or char it really doesn't matter, look at the following code:


vector<point> v = {{1,2},{3,4}};   

vector<point>::iterator it = v.begin();

 while(it != v.end()){

       cout << (*it).x <<","<<(*it).y<<endl;     

       it++;

 }


If you have actually compiled such a program, you must have had the experience of not knowing how to define the type of it. In C++11 you can use auto like this:


vector<point> v = {{1,2},{3,4}};   

auto  it  =  v.begin ();

 while(it != v.end()){

       cout << (*it).x <<","<<(*it).y<<endl;     

       it++;

 }


Pay attention to the yellow background, other codes are as usual.


personal opinion


As can be seen from the above description, the auto modifier can indeed help programmers do something, and in some scenarios, they can think less. But even in the iterator example above, although it is not necessary to specify the type when defining it, it is unimaginable to write the code that uses it next without understanding the iterator type.


Personally, I feel that although things are good, they still need to be understood before they are used.
The above is today's article, welcome to like and recommend it to your friends!

To read more updated articles, please scan the QR code below and follow the WeChat public account [Object-Oriented Thinking]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325915997&siteId=291194637