如何在没有数据复制的情况下从指针创建 Eigen VectorXd 对象

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

我有一个双指针,里面存了一些数据

我想直接在指针上创建一个 VectorXd 而不是复制。也就是说,VectorXd 中存储的数据就是指针中存储的数据。他们是共享的。

我知道创建 VectorXd 对象然后将数据从指针复制到其中很容易。我不希望逐个元素复制发生以减少复制开销。它已经被证明是我应用程序中的性能瓶颈。

#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;
}

如果这是一个愚蠢的问题,我深表歉意。谢谢你的时间。

您需要使用 Map 对象:

#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;
}