简体   繁体   中英

How to create a Eigen VectorXd object from pointer without data copy

I have a double pointer, store some data in it.

I want directly create a VectorXd on the pointer without copy. That is, the data stored in VectorXd is just the data stored in pointer. They are shared.

I know it is easy to create a VectorXd object then copy data into it from the pointer. I do not want the element by element copy happen in order to reduce copy overhead. It is already be proved be the performance bolttleneck in my application.

#include <Eigen/Core>
using namespace Eigen;
int main()
{
    double *ptr = new double [100];

    // fill something into pointer ...

    VectorXd vector(ptr); // dicretely construct vector from pointer without data copy

    // using vector for some other calculation... like matrix vector multiple

    delete[] ptr;
    return 0;
}

I apologize if it is a stupid problem. Thanks for your time.

You need to use a Map object:

#include <iostream>
#include <Eigen/Core>

using namespace std;
using namespace Eigen;

int main()
{
    const int N = 100;
    double *ptr = new double[N];
    for (int i = 0; i < N; i++)
    {
        ptr[i] = double(i);
    }
    Map<VectorXd> vector(ptr, N);
    vector *= 2;
    cout << ptr[32] << endl;
    // 64
    delete[] ptr;
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM