【问题标题】:Initialize C++ array2 using constant array1 known at compile time使用编译时已知的常量 array1 初始化 C++ array2
【发布时间】:2014-07-24 17:46:39
【问题描述】:

我有以下数组:

int const A[4] = { 0, 1, 2, 3 };

我要初始化一个重复数组,如下:

int a[4] = A;

如果我在 cygwin 上运行 g++ 4.8.2 如下:

g++ --std=c++11 myfile.cpp

我收到以下错误:

myfile.cpp:16:16: error: array must be initialized with a brace-enclosed initializer
    int a[4] = A;
               ^

但是,显然“int a[4] = { A };”也不起作用。有没有办法使用简单的赋值语句从A 初始化我的数组a 而无需求助于:

int a[4] = { A[0], A[1], A[2], A[3] };

?

【问题讨论】:

    标签: c++ c++11 compiler-errors constants constant-expression


    【解决方案1】:
    std::copy(A, A+4, a)
    

    或者,通过使用 std::array 有你想要的简单复制方法:

    std::array<int, 4>A = {0, 1, 2, 3}
    std::array<int, 4>a = A;
    

    【讨论】:

    • 谢谢@Ben!我接受了来自莫斯科的@Vlad 只是因为这是我想要的确切答案,但你的答案基本相同,我很感激时间。
    【解决方案2】:

    改用标准类std::array

    #include <array>
    
    //...
    
    const std::array<int, 4> A = { 0, 1, 2, 3 };
    std::array<int, 4 > a = A;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      相关资源
      最近更新 更多