C++ 将 Eigen::VectorXd 类型转换为 std::vector
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26094379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:31:10 来源:igfitidea点击:
typecasting Eigen::VectorXd to std::vector
提问by Manish
Their are many links to go the other way round but I am unable to find to get a std::vector from a Eigen::Matrix or Eigen::VectorXd in my specific case.
他们有很多相反的链接,但在我的特定情况下,我无法从 Eigen::Matrix 或 Eigen::VectorXd 中找到 std::vector 。
回答by ggael
You cannot typecast, but you can easily copy the data:
您无法进行类型转换,但您可以轻松复制数据:
VectorXd v1;
v1 = ...;
vector<double> v2;
v2.resize(v1.size());
VectorXd::Map(&v2[0], v1.size()) = v1;
回答by John Zwinck
vector<int> vec(mat.data(), mat.data() + mat.rows() * mat.cols());
回答by Bastienm
You can do this from and to Eigen vector :
您可以从和到特征向量执行此操作:
//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;
}