C++11赋予了auto新的含义,可以通过auto自动推导变量的类型:
#include <iostream>
using namespace std;
int main(){
auto i = 1;
cout<<"type of i is:"<<typeid(i).name()<<endl;
auto m = 3.14;
cout<<"type of m is:"<<typeid(m).name()<<endl;
auto n = &i;
cout<<"type of n is:"<<typeid(n).name()<<endl;
auto k = i;
cout<<"type of k is:"<<typeid(k).name()<<endl;
auto l = "hello word";
cout<<"type of l is:"<<typeid(l).name()<<endl;
return 0;
}
运行程序输出:
type of i is:i
type of m is:d
type of n is:Pi
type of k is:i
type of l is:PKc
auto可以简化复杂类型的变量定义:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> a = {1, 2, 3, 4};
for(auto i = a.begin(); i < a.end(); i&