我有一个双指针,在其中存储一些数据。
我想直接在指针上创建一个 VectorXd 而无需复制。也就是说,VectorXd 中存储的数据只是指针中存储的数据。它们是共享的。
我知道创建一个 VectorXd 对象然后从指针复制数据很容易。我不希望逐个元素复制发生以减少复制开销。它已经被证明是我的应用程序中的性能 bolt 。
#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;
}
关于c++ - 如何在没有数据复制的情况下从指针创建 Eigen VectorXd 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62791370/