C++11 std - auto

2014-11-24 09:08:33 · 作者: · 浏览: 0

下面是倒序输出字符串的代码:

#include 
  
   
#include 
   
     #include 
    
      #include 
     
       #include 
      
        #include 
       
         using namespace std; int main(int argc, char *argv[]) { freopen("temp.txt","w",stdout); string str("hello world"); //C++98的写法 //for (string::iterator i=str.begin(); it!=str.end(); ++i) //C++11的写法 for(auto i = str.crbegin(); i!=str.crend();i++) { cout<<*i; } while(1); return EXIT_SUCCESS; }
       
      
     
    
   
  

输出结果:

dlrow olleh

分析:

line 15 明显比 line 18行简便

结论:

auto 的主要功能就是是代码更加简洁。下面这段话是出自 《The C++ Standard Library Second Edition》

Using auto is especially useful where the type is a pretty long and / or complicated expression.