C++ - 如何将静态字典制作成查找矩阵

C++ - How to Make Static Dictionary to Lookup Matrix

我正在尝试编写一个 C++ class,它允许我通过字符串查找访问某些矩阵元素。我想创建一个可以做到这一点的 'static' class,例如:

#include <unordered_map>
namespace Mine {
static double AA[3][4] = {
    {5.04964676394959,-0.693207030363152,0.0422140829479668,-0.000968959310672217},
    {2.6044054979329,0.288475262243944,-0.0208805589126506,0.000380899394040856},
    {-4.32707864788065,1.07090008760872,-0.0777874445746693,0.00165150952598117}
};
static unordered_map<std::string, double[3][4]> Mine::parameter_store = { {"AA", AA}};

我的想法是我会有几个矩阵,并且可以根据一个键来查找它们。但是,这似乎完全失败并出现以下错误:

error: object expression of non-scalar type 'double [3][4]' cannot be used in a pseudo-destructor expression

是否可以在 C++ 中以这种方式构建查找 table?

您可以尝试将 double[3][4] 包装在 structure/class

structure myMatrix {
double arr[3][4];
//if you want to initialize it 
myMatrix(double[3][4] p){
   //copy matrix here
}
};
#include <unordered_map>
#include <vector>

namespace Mine{

template<class T>
using Matrix = std::vector<std::vector<T>>;

Matrix<double> AA = {
    {5.04964676394959,-0.693207030363152,0.0422140829479668,-0.000968959310672217},
    {2.6044054979329,0.288475262243944,-0.0208805589126506,0.000380899394040856},
    {-4.32707864788065,1.07090008760872,-0.0777874445746693,0.00165150952598117}
};

static std::unordered_map<std::string, Matrix<double>* > parameter_store = { {"AA", &AA}};
}


#include <iostream>
int main()
{
    std::cout << (*Mine::parameter_store["AA"])[0][0] << std::endl;
    std::cout << (*Mine::parameter_store["AA"])[0][1] << std::endl;
    std::cout << (*Mine::parameter_store["AA"])[1][2] << std::endl;
}

输出

5.04965
-0.693207
-0.0208806

此处使用的 Matrix<> 模板使每一行都存储其长度,即使这是多余的。您可以通过使用 std::array 来避免这种情况(但是由于这是类型信息的一部分,因此您被锁定在具有相同维度的每个矩阵中)或使用像 Boost 这样提供多维数组的库。这是一个非常小的低效率,除非你知道你需要它可能最好不要担心。