数组(一)

81 阅读1分钟

数组

将一到多个相同类型的对象串连到一起,所组成的类型

  1. int a ——> int b[10]

  2. 数组的初始化方式:

    缺省初始化

    聚合初始化 (aggregate initialization)

#include <iostream>
#include <type_traits>

int main()
{
    int a; // int
    int b[10]; // int[10]
    
    std::cout << std::is_same_v<decltype(b), int[10]> << std::endl;  // 1
}

C supports variable sized arrays from C99 standard.

1.PNG

int main()
{
    int a; // int
    int b[1]; // int[1]
    std::cout << std::is_same_v<decltype(b), int[1]> << std::endl;  // 0
}

注意:

  • 不能使用 auto 来声明数组类型;
  • 数组不能复制;
  • 元素个数必须是一个常量表达式 (编译期可计算的值);
  • 字符串数组的特殊性。
int main()
{
    int a[3]; // 默认初始化
    // 聚合初始化, 不足用 0 来补充
    int b[] = {1, 2, 3};
    int c[3] = {1, 2};
}
#include <iostream>
#include <type_traits>
#include <typeinfo>

int main()
{
    auto b = {1, 3, 4};
    std::cout << typeid(b).name() << std::endl;
    std::cout << std::is_same_v<decltype(b), std::initializer_list<int>> << std::endl;
}
#include <iostream>
#include <type_traits>
#include <typeinfo>

int main()
{
    int b[] = {1, 3, 4};
    auto a = b;
    std::cout << std::is_same_v<decltype(a), int*> << std::endl;
}
#include <iostream>
#include <type_traits>
#include <typeinfo>

int main()
{
    char str[] = "Hello";
    // char[5]
    // char str[] = {'H', 'e', 'l', 'l', 'o'};
    std::cout << std::is_same_v<decltype(str), char[6]> << std::endl;
}