c++ - 如何从初始化列表中分配一个数组?

标签 c++ arrays initializer-list

我对 c++ 的了解有限。我尝试编译一个 c++ 库,当我为以下头文件运行 make 文件时

mcmc_dhs.h

#include <algorithm>
#include <map>

// intrinsic shape and (reduced) shear just add?
//#define WLNOISE

// use shear instead of reduced shear for model
//#define NOREDSHEAR

/// parameters for the M200-concentration relation
const number mcreal[2] = {9.59,-0.102}; // Dolag et al. (2004)
//const number mcreal[2] = {5.26,-0.100}; // Neto et al. (2007) [Millenium Run]

/// critical density at z=0 (h100=1) in [Msun/Mpc^3]
const number rhocrit = exp(log(rhoCrit)+3.*log(Mpc)-log(Msun)); 

/// two extra halo parameters: r200 (and concentration: 2)
#define PARAMS 1

/// define region (square; twice value here) about halo that considers sources for model
#define REGION 10.0*arcmin

class mcmc_dhs : public mcmc
{
 public:

  mcmc_dhs() : 
  data(), cosmohandler(0.3,0.7,0.21,0.8,0.04),
    lenseff(), intrvar()
    {
      boundaries = 
    {{0,512},{0,512},{0.01,5.},{100.,3000.},{0.1,50}};
    }
  ~mcmc_dhs() {}

  /// size of grid for looking up sources
  static const int Ngrid = 200;

它返回以下错误信息:

mcmc_dhs.h:55:67: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]
      boundaries = {{0,512},{0,512},{0.01,5.},{100.,3000.},{0.1,50}};
                                                                   ^
mcmc_dhs.h:55:17: error: assigning to an array from an initializer list
      boundaries = {{0,512},{0,512},{0.01,5.},{100.,3000.},{0.1,50}};
                 ^
In file included from ../modules/matrix.h:15:0,
                 from ../modules/probdensity.h:4,
                 from ../modules/mcmc.h:4,
                 from mcmc_dhs.h:4,

最佳答案

不能在数组声明后直接赋值给它。基本上你的代码是一样的

int main()
{
    double arr[2][2];
    arr = { {1, 2}, {3, 4.5} }; // error
}

你必须在声明时赋值

double arr[2][2] = { {1, 2}, {3, 4.5} };

或使用循环(或std::copy)来分配元素。由于你的数组好像是一个成员变量,你也可以在构造函数初始化列表中初始化它:

 mcmc_dhs() : data(), cosmohandler(0.3,0.7,0.21,0.8,0.04), 
              lenseff(), intrvar(), 
              boundaries{{0,512},{0,512},{0.01,5.},{100.,3000.},{0.1,50}}
 { 
    // rest of ctor implementation
 }

关于c++ - 如何从初始化列表中分配一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30178879/

相关文章:

c - C 中 fgets 和 strtok 的问题

c++ - 在不调用 initializer_list 构造函数的情况下将不可复制、不可移动的类型构造为函数参数

c++ - 将具有浮点值的纹理传递给着色器

java - Guava 表与二维数组

c - 自动填充数组

c++ - 有什么方法可以在旧版本的 c++(c++11 之前)中实现初始化列表(某种)?

c++ - C++11 中的混合列表初始化

c++ - 约束编辑控件内容

c++ - 在 C++ 中返回映射的函数

c++ - 未调用 QT 析构函数