数组(五)

102 阅读1分钟
  • 本质:数组的数组

int a[3][4];

#include <iostream>
#include <type_traits>

int main()
{
    int x1[3];
    int x2[3][4];
    
    int x3[3][4][5];   // x3[3] -> int[4][5] 
    
    std::cout << sizeof(int) << std::endl;          // 4
    std::cout << sizeof(x2[0]) << std::endl;        // 16
    // 1
    std::cout << std::is_same_v<decltype(x2[0]), int(&)[4]> << std::endl;
}    
  • 多维数组的聚合初始化:一层大括号 vs 多层大括号

  • 多维数组的索引与遍历

    1. 使用多个中括号来索引
    2. 使用多重循环来遍历
int x2[3][4][5] = {1, 2, 3, 4, 5};
for(auto& p : x2)             // 如果 for(auto p : x2),p 的类型是 int*,不能被遍历
{
    for(auto q : p)
    {
        std::cout << q << '\n';
    }
}
int x2[3][4] = {1, 2, 3, 4, 5};
size_t index0 = 0;
while(index0 < std::size(x2))
{
    size_t index1 = 0;
    while(index1 < std::size(x2[index0]))
    {
        std::cout << x2[index0][index1] << std::endl;
        index1 = index1 + 1;
    }
    index0 = index0 + 1;
}
  • 指针与多维数组

    1. 多维数组可以隐式转换为指针,但只有最高维会进行转换,其它维度的信息会被保留;
    2. 使用类型别名来简化多维数组指针的声明;
    3. 使用指针来遍历多维数组。

1.PNG

#include <iostream>
#include <type_traits>
using A = int[4];

int main()
{
    A x2[3];
    std::cout << std::is_same_v<decltype(x2), int[3][4]> << std::endl;
}
int x2[3][4];
auto ptr = std::begin(x2);
while(ptr != std::end(x2))
{
    auto ptr2 = std::begin(*ptr);
    while(ptr2 != std::end(*ptr))
    {
        std::cout << *ptr2 << std::endl;
        ptr2 = ptr2 + 1;
    }
    ptr = ptr + 1;
}