Search code examples
c++eigen

dynamically allocate memeory for Eigen Vector


I am using the Eigen linear algebra library. I struggling trying to allocate Eigen Vectors in the constructor in a class, and then calling the elements of those vectors.

For example,

#include <Eigen/Dense>
using Eigen::VectorXd;
#include <memory>
using std::unique_ptr;

class Cl
{
public:
    unique_ptr<VectorXd> v;

    Cl(const int n);
    ~Cl(void);
}
Cl::Cl(const int n)
{
    auto v= unique_ptr<VectorXd>(new VectorXd(n));
}
Cl::~Cl(void)
{
    v= nullptr;
}

main(void)
{
    Cl cl(10);

    /* call an element of v how? */

}

For example, using "cl.v(2)" gives me the compiler error (I am using clang++)

error: type 'unique_ptr<VectorXd>' (aka 'unique_ptr<Matrix<double, Dynamic, 1> >') does
      not provide a call operator

while using "cl.(*v)(2)" gives me

error: expected unqualified-id
        cout << cl.(*v)(2) << endl;

I am new to c++, so I may be missing something very basic here.


Solution

  • Why are you trying to dynamically allocate the Eigen::VectorXd v; itself? Unless you would like to extend the lifetime of v beyond the lifetime of cl (in which case you would indeed have to do so), I would recommend to follow the following simple example:

    #include <Eigen/Dense>
    using Eigen::VectorXd;
    
    class Cl
    {
    public:
       VectorXd v;
        Cl(int n) : v(n) {}
        ~Cl() {}
    }
    
    int main()
    {
        Cl cl(10);
        for (int i=0; i<10; ++i)
            cl.v(i) = i;
    }