[英]how to map a Eigen::Matrix to std::vector<Eigen::vector>?
Eg, 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
? 例如,如果我有一个
Eigen::MatrixXd
,其大小为10列和3行,那么如何将其别名为Eigen::Vector3d
的10个元素的std::vector
? 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 :: Matrix,我试图将其转换为Eigen :: vector的向量,但是以下代码行编译失败
Eigen::Matrix2Xd points;
...
std::vector<Eigen::Vector2d> v_points(points.data()
Eigen::aligned_allocator<Eigen::vector2d>(points_data()))
This is possible using a custom allocator as described there: Is it possible to initialize std::vector over already allocated memory? 可以使用如下所述的自定义分配器来实现: 是否可以在已分配的内存上初始化std :: vector?
To this end, you'll have to reinterpret it as a Vector3d*
: 为此,您必须将其重新解释为
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
, eg gsl::span
: 另一种选择是将其包装在类似于
std::vector
某些视图中,例如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
. 在这两种情况下,
mat
对象都必须在std::vector
或span
整个生命周期中保持活动状态。
For completeness, you can also deeply copy it within a std::vector
: 为了完整起见,您还可以在
std::vector
深度复制它:
std::vector<Vector3d> v(10);
Matrix<double,3,Dynamic>::Map(v.data().data(),3,10) = mat;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.