c++11特性
列表初始化
- 使用花括号来初始化对象
 
- 使用列表初始化内置类型的变量,可能会存在丢失信息的风险
 

auto类型说明符号decltype类型说明符
auto
- auto让编译器通过初始值来推算变量的类型
 
- 使用auto也能在一条语句中声明多个变量。因为一条声明语句只能有一个基本数据类型,所以该语句中的所有变量的初始基本数据类型都必须一样
 
- 编译器推断出来的auto类型有时候和初始值的类型并不完全一样,编译器会适当地改变结果类型使其更符合初始化规则
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
   | #include<iostream> #include<typeinfo> using namespace std;
  int main() { 	int a = 33; 	double pi = 3.1415926; 	auto b=a; 	
 
  	cout<<typeid(pi).name()<<endl;     cout<<typeid(a).name()<<endl; 	
  	return 0; }
   | 
 

delctype
- 从表达式的类型推断出要定义的变量的类型,不使用该表达式的值初始化变量
 
- 编译器分析表达式并得到它的类型,却不实际计算表达式的值
 
- 如果decltype使用的表达式不是一个变量,则返回表达式结果对用的类型
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   | #include<iostream> #include<typeinfo> using namespace std;
  int main() { 	int a=1,b=3; 	int &refer_a=a;
  	decltype(a+b) temp=33; 	decltype(refer_a) en=b; 	decltype((a)) refer=b;
 
  	cout<<temp<<" "<<"it's type:'"<<typeid(temp).name()<<endl; 	cout<<refer_a; 	cout<<en<<endl; 	cout<<refer<<endl; 	return 0; }
   | 
 

范围for语句
基本形式:
for(declaration : expression)
    statement
- expression部分是一个对象,用于表示一个序列
 
- declaration部分负责定义一个变量,该变量将被用于访问序列中的基础元素。每次迭代,declaration部分的变量都会被初始化为expression部分的下一个元素值
 
使用范围for语句遍历string对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
   | #include<iostream> using namespace std;
  int main() { 	string str("shan san");
  	 	for(auto s : str) 	{ 	    cout<<s<<" "; 	} 	cout<<endl;
  	for(auto temp : str) 	{ 		cout<<temp; 	} 	cout<<endl;
  	 	for(auto &a : str) 	{ 		a = toupper(a); 	} 	cout<<str<<endl;
  	 	for(decltype(str.size()) index = 0; index != str.size(); ++index) 	{ 		str[index] = toupper(str[index]); 	} 	cout<<str; 	return 0; }
   | 
 

使用范围for语句遍历二维数组
*** 使用范围for语句处理多维数组,除了最内层的循环外,其他所有循环的控制变量都应该是引用类型 ***
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
   | #include<iostream> #include<cstddef> using namespace std;
  int main() {     constexpr size_t rowCnt = 3,colCnt = 4; 	int a[rowCnt][colCnt];
  	 	for(size_t i = 0; i != rowCnt; i++) 	{ 		for(size_t j=0; j != colCnt;j++) 		{ 			 			a[i][j] = i*colCnt + j; 		} 	}
 
  	for(auto &temp : a)            	{ 		for(auto lim :temp)        		{ 			cout<<lim<<endl; 		} 	}     return 0; }
   | 
 
使用范围for语句遍历vector对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   | #include<iostream> #include<vector> using namespace std;
  int main() { 	int scores; 	vector<int> v;
  	while(cin>>scores) 	{ 	    v.push_back(scores); 	}
  	for(auto temp : v) 	{ 		cout<<temp<<" "; 	} 	return 0; }
   | 
 
