C++11/C++14 (三)TYPE INFERENCE (AUTO) AND RANGE-BASED FOR LOOP

PS:以下代码在VS2015中编译通过~~~


#include <iostream>
#include <vector>
using namespace std;


//Type Inference(auto)

//In C++03, we must specify the type of an object when we declare it. 
//Now, C++11 lets us declare objects without specifying their types.
auto a = 1;    // a is an interger
auto b = 2.2;  // b is a double
auto c = a;    // c is an interger


//Also, the keyword auto is very useful for reducing the verbosity of the code. For instance, instead of writing
//for (vector<int>::const_iterator iter = v.begin(); iter != v.end(); ++iter)
//转换为: for(auto iter = v.begin(); iter != v.end(); ++iter)


int main()
{
//The keyword decltype can be used to determine the type of an expression at compile - time.
//For example :


const vector<int> v(1);
auto a = v[0];         // a has type int
decltype(v[1]) b = 1;  // b has type const int&, the return type of
                      // std::vector<int>::operator[](size_type) const
auto c = 0;            // c has type int
auto d = c;            // d has type int


decltype(c) e;         //e has type int, the type of the entity named by c
decltype((c)) f = c;   //f has type int&, because(c) is an lvalue 左值
decltype(0) g;        // g has type int, because 0 is an rvalue
//Note that the type denoted by decltype can be different from the type deduced by auto.




//Range - based for loop
vector<int> v0, v2;
vector<int> v1{ 1, 2, 3, 4, 5 };
//c++03
for (vector<int>::iterator iter = v1.begin(); iter != v1.end(); ++iter)
{
v0.push_back(*iter);
}
//c++11
for (auto iter = v1.begin(); iter != v1.end(); ++iter)
{
v2.push_back(*iter);
}


for (int i : v0)
{
cout << i << endl;  
}


for (auto &i : v2)
{
i *= 10;
cout << i << endl;
}






system("pause");
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值