如何将Eigen :: Matrix映射到std :: vector< Eigen :: vector&gt ;? [英] how to map a Eigen::Matrix to std::vector<Eigen::vector>?

查看:669
本文介绍了如何将Eigen :: Matrix映射到std :: vector< Eigen :: vector&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个 Eigen :: MatrixXd ,其大小为10列和3行,那么如何将其别名为 std ::?向量 Eigen :: Vector3d 的10个元素的向量
当我说别名时,我的意思是使用相同的内存块而不进行复制。

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);

但是相反,如果我有Eigen :: Matrix,我试图将其转换为Eigen :: vector,但以下代码行编译失败

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()))


推荐答案

使用其中所述的自定义分配器可以实现:是否可以初始化

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

为此,您必须将其重新解释为 Vector3d *

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));

另一种选择是将其包装在某些视图中,例如 std :: vector ,例如 gsl :: span

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

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

在两种情况下, mat 对象都必须在 std :: vector span 的整个生命周期内保持生命。

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

出于完整性考虑,您还可以在 std :: vector

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;

这篇关于如何将Eigen :: Matrix映射到std :: vector&lt; Eigen :: vector&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆