C++分配并使用常量作为初始值设定项

C++ assigning and using constant as initializer

本文关键字:分配 常量 C++      更新时间:2023-10-16

请在下面找到我的代码片段:

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;是无效的。

除非您在编译时知道 sz1sz2 的值是什么(在运行程序之前(,否则您不能使用 std::array

您可能希望改用std::vector。像std::vector<std::vector<std::array<double,7>>> lnmat;一样,但请注意,与std::array 不同,向量在初始化时为空。

另外,正如@NathanOliver提到的,对多维数组使用向量的向量可能不是很有效(因为缓存局部性(,如果您的代码对性能敏感,请考虑使用可用作多维数组的单个std::vector,更多详细信息在这里。