下面是倒序输出字符串的代码:
#include <stdio.h>
#include <cstdlib>
#include <string>
#include <iostream>
#include <thread>
#include <array>
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.