C++ 如何创建特征::Ref的向量

C++ 如何创建特征::Ref的向量,c++,vector,reference,eigen3,C++,Vector,Reference,Eigen3,我想引用一个Eigen::MatrixXd中不连续的行。这将作为参数在函数中传递,而不更改MatrixXd(行主)值。 由于我总是需要选择某些行来传递到此函数, 我想我可以使用所选行的引用向量 但即使创建这个向量也似乎不可能:点有p.rows()行数,但每一行都是相同的,即p中的最后一行 你能告诉我为什么会发生这种情况以及如何修复它吗 typedef Eigen::Ref<const Eigen::RowVector3d> OctreePoint; typedef std::vect

我想引用一个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;
typedef特征::Ref OctreePoint;
typedef std::向量八叉点;
本征::矩阵xDp;
//从某个文件中加载P
八字点;
对于(int i=0;iP.row(i)
将有一个内部跨距,因为
P
是(与您的假设相反)列主跨距。这使得每个
Eigen::Ref
包含一个临时跨距,其中包含该行的副本(即,它不是实际引用)

这里基本上有两个选项:

  • 使用
    Eigen::Ref
    获取实际参考
  • 使用
    特征::矩阵P;
  • 下面是一个使用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';
    

    一般来说,我会非常谨慎地将不可复制的成员存储到
    std::vector
    ——只要您将
    推回到
    (或者更好地
    安置回到
    ),一切都应该很好。如果开始在向量中移动元素,编译将失败或可能导致奇怪的结果。

    谢谢你的回答。提供的解决方案解决了这个问题。我不确定我是否理解为什么点中的旧元素会被临时元素替换。
     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