《C++ Primer》练习3.43-3.45: 打印二维数组的元素

本文来自于《C++ Primer》的练习3.43-3.45,觉得多维数组的遍历有不同的实现方式,于是记录一下。写的可能没有按题目的顺序来。题目大概含义是定义了一个二维数组的元素,要求按照行列打印出来(用不同的方式)。

在这里插入图片描述

初始代码

#include <iostream>
#include <iterator>
using namespace std;
int main()
{
  int a[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
  
  \*
  write your code
  *\
}

输出结果

在这里插入图片描述

1. 使用范围for循环

这里使用auto关键字

#include <iostream>
#include <iterator>
using namespace std;
int main()
{
  int a[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
  
  for (auto &p : a)
  {
    for (auto &q : p)
      cout << q << ' ';
    cout << endl;
  }
}

p和q的类型是什么?

auto &p ↔ \leftrightarrow int (&p)[4] ,代表一个引用,引用对象是整型的长度为4的数组
auto &q ↔ \leftrightarrow int (&q) ,代表一个引用,引用对象是整型
上面的代换可以直接代入代码中。

2. 使用普通for循环

2.1 使用指针

使用指针有两种方式:

一种方式是直接进行指针操作

#include <iostream>
#include <iterator>
using namespace std;
int main()
{
  int a[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
  
  for (auto p = a; p != a + 3; ++p)
  {
    for (auto q = *p; q != *p + 4; ++q)
      cout << *q << ' ';
    cout << endl;
  }
}

另一种方式是使用标准库函数beginend得到数组的头元素指针和尾后元素指针(数组最后一个元素后一个位置的指针):

#include <iostream>
#include <iterator>
using namespace std;
int main()
{
  int a[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
  
  for (auto p = begin(a); p != end(a); ++p)
  {
    for (auto q = begin(*p); q != end(*p); ++q)
      cout << *q << ' ';
    cout << endl;
  }
}

p和q的类型是什么?

auto p ↔ \leftrightarrow int (*p)[4] ,代表一个指针,指向的对象是整型的长度为4的数组
auto q ↔ \leftrightarrow int (*q) ,代表一个指针,指向的对象是整型

2.2 使用数组下标

#include <iostream>
#include <iterator>
using namespace std;
int main()
{
  int a[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
  
  for (size_t i = 0; i != 3; ++i)
  {
    for (size_t j = 0; j != 4; ++j)
      cout << a[i][j] << ' ';
    cout << endl;
  }
}

上面的p对应的类型是int[4](长度是4的整型数组),我们可以使用类型别名简化。

类型别名的简化

这里以指针为例,引用也是一样的

第一种写法用的是using关键字

#include <iostream>
#include <iterator>
using namespace std;
using int_array = int[4];
// typedef int int_array[4];
int main()
{
  int a[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};

  for (int_array *p = a; p != a + 3; ++p)
  {
    for (int *q = *p; q != *p + 4; ++q)
      cout << *q << ' ';
    cout << endl;
  }
}

另一种写法是使用typedef关键字

#include <iostream>
#include <iterator>
using namespace std;
typedef int int_array[4];
int main()
{
  int a[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};

  for (int_array *p = a; p != a + 3; ++p)
  {
    for (int *q = *p; q != *p + 4; ++q)
      cout << *q << ' ';
    cout << endl;
  }
}

参考

  1. 《C++ Primer》112-116
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值