C++分配并使用常量作为初始值设定项
C++ assigning and using constant as initializer
请在下面找到我的代码片段:
std::vector<int> idx1;
std::vector<int> idx2;
framx[0].get_idx_of(atm1,idx1);
framx[0].get_idx_of(atm2,idx2);
std::vector<bool> iniz;
const int sz1=idx1.size();
const int sz2=idx2.size();
array<array<array<double,7>,sz2>,sz1> lnmat;
请在使用 C++ 和 clang++ 编译时找到错误。
analysis.cpp:408:33: error: the value of ‘sz2’ is not usable in a constant expression
array<array<array<double,7>,sz2>,sz1> lnmat;
^~~
analysis.cpp:407:15: note: ‘sz2’ was not initialized with a constant expression
const int sz2=idx2.size();
^~~
analysis.cpp:408:36: error: the value of ‘sz2’ is not usable in a constant expression
array<array<array<double,7>,sz2>,sz1> lnmat;
^
analysis.cpp:407:15: note: ‘sz2’ was not initialized with a constant expression
const int sz2=idx2.size();
^~~
analysis.cpp:408:36: note: in template argument for type ‘long unsigned int’
array<array<array<double,7>,sz2>,sz1> lnmat;
^
analysis.cpp:408:38: error: the value of ‘sz1’ is not usable in a constant expression
array<array<array<double,7>,sz2>,sz1> lnmat;
^~~
analysis.cpp:406:15: note: ‘sz1’ was not initialized with a constant expression
const int sz1=idx1.size();
^~~
analysis.cpp:408:41: error: template argument 1 is invalid
array<array<array<double,7>,sz2>,sz1> lnmat;
^
analysis.cpp:408:41: error: the value of ‘sz1’ is not usable in a constant expression
analysis.cpp:406:15: note: ‘sz1’ was not initialized with a constant expression
const int sz1=idx1.size();
^~~
analysis.cpp:408:41: note: in template argument for type ‘long unsigned int’
array<array<array<double,7>,sz2>,sz1> lnmat;
你能告诉我变量 lnmat 分配错误的原因吗?似乎数组声明可能没有标识常量,或者它的声明存在一些问题。
PS:请不要让我回答这个问题。
std::array
编译时必须知道第二个模板参数。
您正在使用仅在运行时已知的常量,即:
const int sz1=idx1.size();
const int sz2=idx2.size();
所以std::array<array<array<double,7>,sz2>,sz1> lnmat;
是无效的。
除非您在编译时知道 sz1
和 sz2
的值是什么(在运行程序之前(,否则您不能使用 std::array
。
您可能希望改用std::vector
。像std::vector<std::vector<std::array<double,7>>> lnmat;
一样,但请注意,与std::array
不同,向量在初始化时为空。
另外,正如@NathanOliver提到的,对多维数组使用向量的向量可能不是很有效(因为缓存局部性(,如果您的代码对性能敏感,请考虑使用可用作多维数组的单个std::vector
,更多详细信息在这里。
相关文章:
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 如何为静态常量模板化专用整数值分配存储
- 将编译时常量向量转换为堆分配版本
- 对复合分配中的"常量"的混淆
- 传入与在C++中分配常量引用
- 将常量字符* 分配给字符*
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 移动具有常量成员的类的构造和分配
- cpp 数组 - 分配常量索引有效,而非常量索引不起作用
- C++:可以编写忽略常量分配的代码吗?
- C++ - 无法将顶部常量指针分配给另一个非常量指针
- 为什么在将常量 ptr 分配给常量引用时没有收到编译错误?
- 可选参数常量引用重新分配
- C++分配并使用常量作为初始值设定项
- 如何在C++中将常量引用分配给函数中的指针
- 使用函数中的语句数作为内存分配的常量
- 如何在c++中为指针分配常量地址
- 从头文件 c++ 内的常量二维数组行分配常量 1D 数组
- 预期的常量表达式,不能分配常量大小为0的数组
- 不能分配常量大小为0的数组