Initialise Eigen::vector with std::vector

前端 未结 5 1314
独厮守ぢ
独厮守ぢ 2020-12-01 01:59

I have seen it done before but I cannot remember how to efficiently initialize an Eigen::Vector of known length with a std::vector of the same leng

5条回答
  •  孤城傲影
    2020-12-01 02:25

    According to Eigen Doc, Vector is a typedef for Matrix, and the Matrix has a constructor with the following signature:

    Matrix (const Scalar *data)
    

    Constructs a fixed-sized matrix initialized with coefficients starting at data.

    And vector reference defines the std::vector::data as:

    std::vector::data
    
    T* data();
    const T* data() const;
    

    Returns pointer to the underlying array serving as element storage. The pointer is such that range [data(); data() + size()) is always a valid range, even if the container is empty.

    So, you could just pass the vector's data as a Vector3d constructor parameter:

    Eigen::Vector3d v2(v1.data());
    

    Also, as of Eigen 3.2.8, the constructor mentioned above defined as:

    template
    inline Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>
      ::Matrix(const Scalar *data)
    {
      this->_set_noalias(Eigen::Map(data));
    }
    

    As you can see, it also uses Eigen::Map, as noted by @ggael and @gongzhitaao.

提交回复
热议问题