how to map a Eigen::Matrix to std::vector<Eigen::vector>?

谁说胖子不能爱 提交于 2019-12-25 03:25:06

问题


E.g., if I have an Eigen::MatrixXd of size 10 columns and 3 rows, how can I alias that to a std::vector of 10 elements of Eigen::Vector3d? when I say alias I mean using the same memory block without copying.

I know that I can do the reversed mapping by something like:

std::vector<Vector3d> v(10);
...
Map<Matrix<double,3,Dynamic> >  m(v.data().data(), 3, 10);

but reversely, if I have an Eigen::Matrix, I tried to convert it to a vector of Eigen::vector but the following code line failed compilation

Eigen::Matrix2Xd points;
...
std::vector<Eigen::Vector2d> v_points(points.data()
    Eigen::aligned_allocator<Eigen::vector2d>(points_data()))

回答1:


This is possible using a custom allocator as described there: Is it possible to initialize std::vector over already allocated memory?

To this end, you'll have to reinterpret it as a Vector3d*:

Vector3d* buf = reinterpret_cast<Vector3d*>(mat.data());

and then pass it to your custom allocator:

std::vector<Vector3d, PreAllocator<Vector3d>> my_vec(10, PreAllocator<Vector3d>(buf, 10));

Another option would be to wrap it within some views alike std::vector, e.g. gsl::span:

gsl::span<Vector3d> view(buf,mat.cols());

In both cases, the mat object must stay alive throughout the lifetime of the std::vector or span.

For completeness, you can also deeply copy it within a std::vector:

std::vector<Vector3d> v(10);
Matrix<double,3,Dynamic>::Map(v.data().data(),3,10) = mat;


来源:https://stackoverflow.com/questions/54682743/how-to-map-a-eigenmatrix-to-stdvectoreigenvector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!