指针和数组

C++11开始,除了提供原始数组形式外,STL容器库还提供了std::array;与此同时,除了提供原始指针形式外,C++还提供了智能指针操作

  • 原始指针
  • 原始数组
  • 指针名和数组名的区别
  • 指针数组
  • 数组指针

一维/二维/三维数组

实现原始数组和std::array的一维/二维/三维创建

    const int LENGTH = 3;
    const int WIDTH = 10;
    const int HEIGHT = 5;

    int a1[LENGTH] = {1, 2, 3};
    int a2[LENGTH][WIDTH]{};
    int a3[LENGTH][WIDTH][HEIGHT]{};

    using std::array;
    array<int, LENGTH> aa1 = {1, 2, 3};
    array<array<int, LENGTH>, WIDTH> aa2{};
    array<array<array<int, LENGTH>, WIDTH>, HEIGHT> aa3{};

使用大括号进行列表初始化,std::array的存储形式是第3维->第2维->第1维(从外到里)

数组大小

打印第一维/第二维/第三维大小

    cout << aa1.size() << endl;
    cout << aa2[0].size() << endl;
    cout << aa3[0][0].size() << endl;

结果如下

3
3
3

数组遍历

通过迭代器方式可以快速遍历std::array

    for (auto it = aa1.begin(); it != aa1.end(); ++it) {
        cout << *it << " ";
    }

结果如下:

1 2 3

或者直接使用for循环

    int i = 0;
    for (auto &items: aa2) {
        for (auto &x: items) {
            x = i + 1;
            i++;
            cout << x << " ";
        }
        cout << endl;
    }

外边的for循环遍历了二维数组aa2的第二维,里面的for循环遍历了第一维。结果如下:

1 2 3 
4 5 6 
7 8 9 
10 11 12 
13 14 15 
16 17 18 
19 20 21 
22 23 24 
25 26 27 
28 29 30