【问题标题】:typecasting Eigen::VectorXd to std::vector将 Eigen::VectorXd 类型转换为 std::vector
【发布时间】:2014-11-23 12:29:01
【问题描述】:

他们有很多链接可以反过来,但在我的具体情况下,我无法从 Eigen::Matrix 或 Eigen::VectorXd 中获取 std::vector。

【问题讨论】:

    标签: c++ eigen


    【解决方案1】:
    vector<int> vec(mat.data(), mat.data() + mat.rows() * mat.cols());
    

    【讨论】:

    • mat.rows() * mat.cols() 可以简化为 mat.size(),但是请注意,此解决方案仅适用于普通的 Matrix&lt;&gt; 对象,而在我的答案中使用 Map&lt;&gt; 适用于子矩阵也是。
    • 如果有人需要将一行矩阵复制到一个向量中:vector&lt;double&gt; vec(arr.cols()); Map&lt;RowVectorXd&gt;(&amp;vec[0], 1, mat.cols()) = mat.row(0);
    【解决方案2】:

    您无法进行类型转换,但您可以轻松复制数据:

    VectorXd v1;
    v1 = ...;
    vector<double> v2;
    v2.resize(v1.size());
    VectorXd::Map(&v2[0], v1.size()) = v1;
    

    【讨论】:

    • 嘿,谢谢你的回复.. 但我发现上面的答案更干净。
    【解决方案3】:

    您可以从特征向量到特征向量执行此操作:

        //init a first vector
        std::vector<float> v1;
        v1.push_back(0.5);
        v1.push_back(1.5);
        v1.push_back(2.5);
        v1.push_back(3.5);
    
        //from v1 to an eignen vector
        float* ptr_data = &v1[0];
        Eigen::VectorXf v2 = Eigen::Map<Eigen::VectorXf, Eigen::Unaligned>(v1.data(), v1.size());
    
        //from the eigen vector to the std vector
        std::vector<float> v3(&v2[0], v2.data()+v2.cols()*v2.rows());
    
    
        //to check
        for(int i = 0; i < v1.size() ; i++){
            std::cout << std::to_string(v1[i]) << " | " << std::to_string(v2[i]) << " | " << std::to_string(v3[i]) << std::endl;
        }
    

    【讨论】:

    • v1.data() 应该换成ptr_data,不是吗?
    猜你喜欢
    • 2021-11-16
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2021-10-30
    • 2019-07-08
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多