C++ primer 5 3.6节练习:遍历二维数组的各种形式

    xiaoxiao2021-03-25  50

    #include <iostream> #include <cstring> #include <vector> using namespace std; int main() { size_t cnt = 0; const int row = 5, col = 6; int a[row][col] = { 0 }; using int_arry = int[col];//类型别名声明 /**初始化二维数组a**/ for (auto &r:a) for (auto &c : r) { c = cnt; cnt++; } /*****版本1,范围for遍历二维数组*****/ cout << "版本1,范围for:" << endl; for (int (&p)[col]:a)//注意:此时的p是一个col个整数的数组的引用,即类型不再是int &p而是int (&p)[5] { for (int &q:p) cout << q << " "; cout << endl; } cout << endl; /*****版本2,普通for遍历二维数组*****/ cout << "版本2,下标运算符遍历:" << endl; for (size_t p1 = 0; p1 != row; ++p1) { for (size_t q1 = 0; q1 != col; ++q1) cout << a[p1][q1] << " "; cout << endl; } cout << endl; /*****版本3,普通for遍历二维数组*****/ cout << "版本3,指针遍历:" << endl; for (int(*p2)[col] = begin(a); p2 != end(a); p2++)//同样,如同版本1 p2是一个指向有col个整数的数组的指针,即类型是int (*p2)[col] { for (int *q2 = begin(*p2); q2 != end(*p2); q2++)//对于q2则是一个整数指针,因为每个col个整数的数组中的元素为整数 cout << *q2 << " "; cout << endl; } cout << endl; /*版本4,用类型别名遍历改写版本1,版本3*/ cout << "版本4,类型别名改写版本1:" << endl; for (int_arry &p3 : a)//即int_arry &p3 = int (&p3)[col] { for (int &q3 : p3) cout << q3 << " "; cout << endl; } cout << endl; /*版本4,用类型别名遍历改写版本3*/ cout << "版本5,类型别名改写版本3:" << endl; for (int_arry *p4 = begin(a); p4 != end(a); p4++) { for (int *q4 = begin(*p4); q4 != end(*p4); q4++) cout << *q4 << " "; cout << endl; } cout << endl; system("pause"); return 0; }

    结果如下:

    转载请注明原文地址: https://ju.6miu.com/read-33885.html

    最新回复(0)