4.9,4.10
4.9类型组合
1 #include<iostream> 2 struct years 3 { 4 int year; 5 }; 6 7 int main() 8 { 9 using namespace std; 10 11 years s1,s2,s3; 12 s1.year=1998; 13 14 years *pa=&s2; 15 pa->year=1999; 16 17 years trio[3];//array of 3 structures 18 trio[0].year=2003; 19 cout<<trio->year<<endl; 20 21 const years *arp[3]={&s1,&s2,&s3}; 22 cout<<arp[1]->year<<endl; 23 24 const years **ppa=arp; 25 auto ppb=arp;//c++11 automatic type deduction 26 cout<<(*ppa)->year<<endl; 27 cout<<(*(ppa+1))->year<<endl; 28 29 return 0; 30 }
4.10数组的替代品
vector
头文件<vector>,使用using namespace std
1 #include<vector> 2 using namespace std; 3 vector<int> vi;//设置初始长度为0 4 int n; 5 cin>>n; 6 vector<double> vd(n);//n个double的数组
模板:vector<typename>vt<n_elem>
n_elem可以是常量也可以是变量
array(c++11)
头文件<array>,使用using namespace std;
1 #include<array> 2 using namespace std; 3 array<int,5>ai; 4 array<double ,a>ad={1.2,2.1,6.43,6.5};
模板:array<typename,n_elem>arr;
n_elem不能使变量。
例子:
1 #include<iostream> 2 #include<vector> 3 #include<array> 4 int main() 5 { 6 using namespace std; 7 double a[4]={1.2,2.4,3.6,4.8}; 8 9 vector<double>b(4); 10 b[0]=1.0/3.0; 11 b[1]=1.0/5.0; 12 b[2]=1.0/7.0; 13 b[3]=1.0/9.0; 14 15 array<double,4>c={3.14,2.72,1.62,1.41}; 16 array<double,4>d; 17 d=c; 18 19 cout<<"a[2]:"<<a[2]<<" at "<<&a[2]<<endl; 20 cout<<"b[2]:"<<b[2]<<" at "<<&b[2]<<endl; 21 cout<<"c[2]:"<<c[2]<<" at "<<&c[2]<<endl; 22 cout<<"d[2]:"<<d[2]<<" at "<<&d[2]<<endl; 23 24 a[-2]=20.2;//危¡ê险? 25 cout<<"a[-2]:"<<a[-2]<<" at "<<&a[-2]<<endl; 26 cout<<"c[2]:"<<c[2]<<" at "<<&c[2]<<endl; 27 cout<<"d[2]:"<<d[2]<<" at "<<&d[2]<<endl; 28 29 return 0; 30 }
a[-2]=20.2;
意思是a所指的位置向前移2个位,存储20.2,存储在数组外面。c++并不检查这种越界错误。这种行为是很危险的。