2014-09-29 47 views

回答

19
vector<int> vec(mat.data(), mat.data() + mat.rows() * mat.cols()); 
+0

謝謝你,它的工作。我可以知道你是如何到達解決方案的嗎? – 2014-09-29 09:31:34

+2

'mat.rows()* mat.cols()'可以簡化爲'mat.size()',但是,請注意,這種解決方案只適用於普通的'Matrix <>'對象,而使用'Map <>'在我的答案中也適用於子矩陣。 – ggael 2014-09-29 10:58:13

30

你不能強制轉換,但你可以很容易地複製數據:

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

heyy謝謝你的回覆..但我發現上面的答案更乾淨。 – 2014-09-29 09:34:01

+3

不錯,因爲它可以在兩種方式下工作(從和到VectorXd) – Raffi 2015-04-01 14:40:25

1

你可以從和特徵向量做到這一點:

//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; 
    }