0
votes

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
no it is not, i want the reversed conversionshelper

1 Answers

2
votes

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;