Eigen与std::vector转换 - yuhannah/skills_map GitHub Wiki

Eigen::Vector或者Eigen::Matrix<type,Dynamic,1>能与std::vector直接转换。 Eigen::Matrix<type,row,col>不知道如何与std::vector直接转换。但可以先转换成Eigen::Vector。

void test()
{
    //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);
    for (auto &it : v1) {
        cout << it << ",";
    }
    cout << endl;

    //from v1 to an eigen vector
    Eigen::VectorXf v2 = Eigen::Map<Eigen::VectorXf, Eigen::Unaligned>(v1.data(), v1.size());
    Eigen::VectorXf v22 = Eigen::Map<Eigen::VectorXf, Eigen::Unaligned>(const_cast<float*>(&v1[0]), v1.size());

    //from the eigen vector to the std vector
    std::vector<float> v3(&v2[0], v2.data() + v2.cols() * v2.rows());
    for (auto &it : v3) {
        cout << it << ",";
    }
    cout << endl;

    //from v1 to an eigen matrix
    Eigen::Matrix<float,Eigen::Dynamic,1> v4 = Eigen::Map<Eigen::Matrix<float,Eigen::Dynamic,1>, Eigen::Unaligned>(v1.data(), v1.size(), 1);
    Eigen::Matrix<float,Eigen::Dynamic,1> v44 = Eigen::Map<Eigen::Matrix<float,Eigen::Dynamic,1>, Eigen::Unaligned>(
            const_cast<float*>(&v1[0]), v1.size(), 1);

    //from the eigen matrix to the std vector
    std::vector<float> v5(&v4[0], v4.data() + v4.cols() * v4.rows());
    for (auto &it : v5) {
        cout << it << ",";
    }
    cout << endl;

    //from v1 to an eigen matrix
    Eigen::Matrix2f v6 = Eigen::Map<Eigen::Matrix2f, Eigen::Unaligned>(v2.data(), 2, 2);
    Eigen::Matrix2Xf v66 = Eigen::Map<Eigen::Matrix2Xf, Eigen::Unaligned>(
            const_cast<float*>(&v1[0]), 2, (v1.size() / 2));

    //from eigen matrix to eigen vector
    Eigen::VectorXf v7 = Eigen::Map<Eigen::VectorXf>(v6.data(), v6.size()/*v6.cols() * v6.rows()*/);

    //from the eigen matrix to the std vector
    std::vector<float> v8(&v7[0], v7.data() + v7.cols() * v7.rows());
    for (auto &it : v8) {
        cout << it << ",";
    }
    cout << endl;
}
⚠️ **GitHub.com Fallback** ⚠️