0

I am using Eigen for some linear algebra calculations and I am at a point where I need to interface this with another codebase, which is not aware of Eigen and is using std::vector<double> rather than an Eigen::VectorXd internally for storing elements in memory. The following (simplified) code is where the problems appear:

void solve(std::vector<double> &vec) {
    Eigen::BiCGSTAB<Eigen::SparseMatrix<double>, Eigen::IncompleteLUT<double>> solver;
    Eigen::VectorXd rhs(vec.size());
    vec = solver.solve(rhs);
}

Here, I am passing in a std::vector as a reference and I want this variable (vec) to be updated as part of the solution process, (i.e. as part of the last instruction vec = solver.solve(rhs);). This, however, returns an Eigen vector so the above will not compile.

Two things to note: I am expecting the function void solve() to be called several thousand times per program execution and vec can hold several million elements. Thus, copying data is not an option.

The question then is how to map the data from Eigen to a std::vector. I feel that either using one of Eigen's internal functionality (Eigen::Map, Eigen::Ref?) may be of help here or to transform the std::vector into a shared pointer, though the solution I tried don't seem to work. I have also looked at using a reinterpret_cast on the raw data of both the std::vector and Eigen::VectorXd to no avail. I feel this should be possible but can't see how, at the moment.

This question is similar to the following posts:

In the above questions, however, performance overhead does not seem to be critical, i.e. here they only need to initialise the data structure, whereas I need to keep two separate std::vector and Eigen::VectorXd throughout the execution of my program.

tom
  • 361
  • 3
  • 11
  • Maybe you can take some inspiration from this upcoming C++23 feature (mdspan): [Multidimensional C++ - Bryce Adelstein Lelbach - CppNorth 2022](https://www.youtube.com/watch?v=aFCLmQEkPUw). – Pepijn Kramer Oct 23 '22 at 17:11
  • 2
    ```Eigen::Map``` does not copy any data and can directly reference the memory managed by an ```std::vector```. So the second answer you linked (https://stackoverflow.com/questions/57843878/map-from-stdvectorunsigned-to-eigenvectorxi) directly applies and solves your problem. So, which part of it is unclear? – Homer512 Oct 23 '22 at 17:34
  • you are right, I may have misread the first part of the answer (about copying), just checked, Eigen::Map does what I need, cheers! – tom Oct 23 '22 at 22:23

0 Answers0