3.43
auto功能的强大让我叹为观止 。。简直就是让你随心所欲。。。
版本一:使用范围for语句,最重要注意的是使用引用!!!!!!!!!!
#include<iostream>
using namespace std;
int main()
{
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
for(int (&i)[4] : a) //i对含四个整数的数组的引用。借以表示二维数组a的最内层元素 。。。
for(int j:i) // 从每个元素 遍历其含有的4个整数。
cout<<j<<" ";
return 0;
}
版本二
使用数组下标,太简单。
#include<iostream>
#include<vector>
#include<string>
#include<cstdlib>
using namespace std;
int main()
{
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
for(int i=0;i<3;++i)
for(int j=0;j<4;++j)
cout<<a[i][j]<<" ";
return 0;
}
版本三
使用指针。。有点意思,注意指针指的东西尤为重要!!!
#include<iostream>
using namespace std;
int main()
{
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
for(int (*p)[4]=a;p!=a+3;++p)
for(int* q=*p;q!=(*p)+4;++q)
cout<<*q<<" ";
return 0;
}
练习3.44
使用类型别名
版本一
范围for语句 ,使用引用
#include<iostream>
using namespace std;
int main()
{
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
using int_array=int[4];
for(int_array &i : a )
for(int j :i )
cout<<j<<" ";
return 0;
}
版本三
使用指针
#include<iostream>
using namespace std;
int main()
{
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
using int_array=int[4];
for(int_array *p=a;p!=a+3;++p)
for(int* q=*p;q!=(*p)+4;++q)
cout<<*q<<" ";
return 0;
}
3.45
使用auto 实在是太简单。
版本一的范围for语句实在是太简单
版本3 ,指针auto可一看
p=a //a直接赋值给p auto 自动检测,简直简单粗暴。。。
#include<iostream>
using namespace std;
int main()
{
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
for(auto p=a;p!=a+3;++p )
for(auto q=*p;q!=(*p)+4;++q)
cout<<*q<<" ";
return 0;
}
关于多维数组,我想2维仅仅是个开始,但如果3维以上呢。。。你有去思考过吗
3维的情况下。
版本一使用范围for语句,不使用auto。。
分清楚引用引用的是什么,这点很重要
#include<iostream>
using namespace std;
int main()
{
int a[2][2][3]={1,2,3,4,5,6,7,8,9,10,11,12};
for(int (&i)[2][3] : a)
for(int (&j)[3] : i)
for(int k : j)
cout<<k<<" ";
return 0;
}
版本3
使用指针
能分清楚 指针指的是什么。。
#include<iostream>
using namespace std;
int main()
{
int a[2][2][3]={1,2,3,4,5,6,7,8,9,10,11,12};
for(int (*p)[2][3]=a;p!=a+2;++p) //p指向一个有2个元素,每个元素含3个整数的数组。。 p即3维a的最内层数组的指针
for(int (*q)[3]=*p;q!=(*p)+2;++q) // *p即为 一个有2个元素,每个元素含3个整数的数组的 第一个元素地址,
for(int *k=*q;k!=(*q)+3;++k) // q指向含3个整数的数组的地址
cout<<*k<<" "; // *q为指向含3个整数的数组的首地址
return 0;
}
版本3
使用类型别名 using
#include<iostream>
using namespace std;
int main()
{
int a[2][2][3]={1,2,3,4,5,6,7,8,9,10,11,12};
using int_1=int[2][3];
using int_2=int[3];
for( int_1 *p=a; p!=a+2;++p)
for( int_2 *q=*p;q!=(*p)+2;++q)
for(int *k=*q;k!=(*q)+3;++k)
cout<<*k<<" ";
return 0;
}
版本四
使用类型别名 typedef
#include<iostream>
using namespace std;
int main()
{
int a[2][2][3]={1,2,3,4,5,6,7,8,9,10,11,12};
typedef int int_1[2][3];
typedef int int_2[3];
for( int_1 *p=a; p!=a+2;++p)
for( int_2 *q=*p;q!=(*p)+2;++q)
for(int *k=*q;k!=(*q)+3;++k)
cout<<*k<<" ";
return 0;
}
版本五
使用强大的auto
#include<iostream>
using namespace std;
int main()
{
int a[2][2][3]={1,2,3,4,5,6,7,8,9,10,11,12};
for(auto &i : a)
for(auto &j :i)
for(auto k : j)
cout<<k<<" ";
return 0;
}