planB...

导航

3.6节练习

练习3.43

 1 #include "stdafx.h"
 2 #include <iostream>
 3 using namespace std;
 4 int _tmain(int argc, _TCHAR* argv[])
 5 {
 6     int ia[3][4] = {
 7         {0,1,2,3},
 8         {4,5,6,7},
 9         {8,9,10,11}
10     };    
11     //版本一
12     for (int (&p)[4]:ia)//p指向含有四个元素的数组
13                         //为什么这里不用(*p)[4],因为ia的基本元素是指向四个
14                         //元素的数组
15     {
16         for (int q:p)//q指向一个整数
17         {
18             cout << q << " ";
19         }
20     }
21     cout << endl;
22     //版本二
23     for (size_t i = 0; i < 3; ++i)
24     {
25         for (size_t j = 0; j < 4; ++j)
26         {
27             cout << ia[i][j] << " ";
28         }
29     }
30     cout << endl;
31     //版本三
32     int (*d)[4] = ia;
33     for (size_t i = 0; i < 3; ++i)
34     {
35         for (size_t j = 0; j < 4; ++j)
36         {
37             cout << (*(d + i))[j] << " ";
38             //这里还犯了一个错误,当时写了(*d + i)[j],结果输出来不正确,经过
39             //思考才知道(*d+i)是指*d这个指针所指的元素的下一个元素,而不是
40             //指针d的下一个位置
41         }
42     }
43     cout << endl;
44 }

练习3.44

 1 #include "stdafx.h"
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 int _tmain(int argc, _TCHAR* argv[])
 7 {
 8     int ia[3][4] = {
 9         {0,1,2,3},
10         {4,5,6,7},
11         {8,9,10,11}
12     };    
13     using int_array = int[4];
14     for (int_array *p = ia; p!= ia+3; ++p)//p是一个指向四个元素的指针
15     {
16         for (int *q = *p; q!= *p + 4; ++q)//q是p指向的四个元素的第一个
17         {
18             cout << *q << endl;
19         }
20     }
21 }

练习3.45

 1 #include "stdafx.h"
 2 #include <iostream>
 3 using namespace std;
 4 int _tmain(int argc, _TCHAR* argv[])
 5 {
 6     int ia[3][4] = {
 7         {0,1,2,3},
 8         {4,5,6,7},
 9         {8,9,10,11}
10     };    
11     for (auto &p : ia)
12     {
13         for (auto &q:p)
14         {
15             cout << q << endl;
16         }
17     }
18 }

 

posted on 2015-10-31 22:56  ianobot  阅读(117)  评论(0)    收藏  举报