C++ 犰狳:从 vector<vector 初始化 mat <double>> 破坏数据



我正在尝试初始化从矢量到armadillo mat的数据。

发现这个网站解释如何做到:

http://www.kaiyin.co.vu/2014/07/initialize-armadillo-matrix-with-std.html

在打印了向量中的向量和生成的mat之后,我得出结论,armadillo会把我的数据变成垃圾。

我的主要功能部分:

 vector<vector<double>> C_mat(num_of_functions,vector<double>(num_of_points));
        for(int j=0; j< num_of_functions; ++j)
        {
            for( int i=0;i<num_of_points; ++i)
            {
                C_mat[j][i]=(functions[j](points[i].x()));// shouldn't bother you, this works. 
            }
        }
        mat C(&(C_mat.front()).front(),num_of_points, num_of_functions);
        cout << C << endl << endl;
        for(int i=0; i< num_of_functions;++i)
        {
            print_vec(C_mat[i]);
        }

print_ve(vector)是我编写的一个函数,用于打印向量。

输出:

    1.0000e+00        0e+00   1.9965e+01
    1.0000e+00  4.7924e-322   1.2822e+00
    1.0000e+00   1.1683e+01        0e+00
    1.0000e+00   1.6936e+01  4.7924e-322
    1.0000e+00   2.3361e-01   1.0237e+02
    1.0000e+00   1.6445e+01   2.1512e+02
    1.0000e+00   7.4271e+00   4.0931e-02
    1.0000e+00   1.4162e+01   2.0284e+02
    1.0000e+00   1.1670e+01   4.1371e+01
    1.0000e+00   2.3633e+00   1.5042e+02

打印矢量:

11.1.1.1.1.1.1.1.1

打印矢量:

11.682816.93590.23361316.44557.4270814.161911.67012.3632919.96531.28223

打印矢量:

102.366215.1190.0409313202.8441.3711150.421102.1434.18885298.9591.23308

更新:

我试着根据第一个注释更改代码,基本上是用1D向量制作自己的2D向量。现在armadillo并没有破坏数据,而是扰乱数据:

        vector<double> C_mat(num_of_functions*num_of_points);   
        for( int i=0;i<num_of_points; ++i)
        {
            for(int j=0; j< num_of_functions; ++j)
            {
                    C_mat[i*num_of_functions+j]= functions[j](points[i].x());
            }
        } 
        mat C(&C_mat.front(),num_of_points, num_of_functions);

输出:

     1.0000e+00   1.1170e+01   1.6853e+01
     4.5538e+00   9.3574e+01   1.0000e+00
     1.5553e+01   1.0000e+00   1.6292e+01
     1.0000e+00   8.7956e-01   1.9907e+02
     6.0653e+00   5.8021e-01   1.0000e+00
     2.7591e+01   1.0000e+00   1.0787e+01
     1.0000e+00   1.8169e+01   8.7269e+01
     1.3849e+01   2.4758e+02   1.0000e+00
     1.4385e+02   1.0000e+00   1.7998e+01
     1.0000e+00   4.7403e+00   2.4295e+02

   1  4.5538  15.5528 
   1  6.06532  27.5911 
   1  13.8494  143.854 
   1  11.1698  93.574 
   1  0.879557  0.580215 
   1  18.1687  247.577 
   1  4.74031  16.8529 
   1  16.2919  199.069 
   1  10.787  87.2695 
   1  17.998  242.945 

std::vector等同于数据指针和长度(以及一些无关的东西)。指针指向存储实际元素的一堆内存。第0个元素被存储在地址pointer,第N个元素被保存在pointer+N。这就是为什么Armadillo mat构造函数可以采用第一个元素的地址和长度来构造矩阵。

当你制作一个向量时,你会得到num_of_functions个内部向量,每个向量都有自己的数据指针。这意味着数据不存储在连续存储器中。

要初始化std::vector的二维矩阵,您应该创建大小为num_of_functions*num_of_points的矩阵,并按列主顺序存储值。

最新更新