如何创建Eigen :: Ref的向量

问题描述 投票:1回答:1

我想引用Eigen :: MatrixXd中的不连续行。这将作为函数中的参数传递,而不更改MatrixXd(行主要)值。由于我总是需要选择某些行来传递给这个函数,我想我可以使用一个引用向量来选择行。

但即使创建此向量似乎也是不可能的:点有P.rows()行数但每行都相同,即P中的最后一行。

你能告诉我为什么会这样,以及如何解决它?

typedef Eigen::Ref<const Eigen::RowVector3d> OctreePoint;
typedef std::vector<OctreePoint> OctreePoints;

Eigen::MatrixXd P;
// load P from some file
OctreePoints points; 
for (int i = 0; i < P.rows(); ++i)
    {
            // OctreePoint p = P.row(i);
        points.push_back(P.row(i));
        // std::cout << p << std::endl;
     }
std::cout << points << std::endl;
c++ vector reference eigen3
1个回答
1
投票

这里的主要问题是:P.row(i)将有一个内在的步伐,因为P(与你的假设相反)专栏主要。这使得每个Eigen::Ref包含一个临时表,其中包含该行的副本(即,它不是实际的引用)。

你基本上有两个选择:

  1. 使用Eigen::Ref<const Eigen::RowVector3d, 0, Eigen::InnerStride<> >获取实际参考。
  2. 使用P制作Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> P; rowmajor

这是一个使用(非const)变体1的例子:

    typedef Eigen::Ref<Eigen::RowVector3d, 0, Eigen::InnerStride<> > OctreePoint;
    typedef std::vector<OctreePoint> OctreePoints;

    // Alternatively, use this for P:
    // Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> P;
    Eigen::MatrixXd P;
    P.setRandom(3,3);
    std::cout << P << " @ " << P.data() << "\n\n";
    OctreePoints points;
    points.reserve(1);
    for (int i = 0; i < P.rows(); ++i)
    {
        points.push_back(P.row(i));
    }
    points[0][0] = 42.0; // Modify an element of `points` for testing purposes

    for(auto p : points ) std::cout << p << " @ " << p.data() << '\n';

    std::cout << '\n' << P << '\n';

这会生成类似以下输出的内容:

 0.680375   0.59688 -0.329554
-0.211234  0.823295  0.536459
 0.566198 -0.604897 -0.444451 @ 0x25b8c20

       42   0.59688 -0.329554 @ 0x25b8c20
-0.211234  0.823295  0.536459 @ 0x25b8c28
 0.566198 -0.604897 -0.444451 @ 0x25b8c30

       42   0.59688 -0.329554
-0.211234  0.823295  0.536459
 0.566198 -0.604897 -0.444451

一般来说,我会非常谨慎地将不可复制的成员存入std::vector - 只要你只是push_back(或更好的emplace_back),一切都应该没问题。如果您开始在向量内移动元素,编译将失败或可能导致奇怪的结果。

© www.soinside.com 2019 - 2024. All rights reserved.