简体   繁体   中英

Create Eigen::Ref from std::vector

It is easy to copy data between eg Eigen::VectorXd and std::vector<double> or std::vector<Eigen::Vector3d> , for example

std::vector<Eigen::Vector3> vec1(10, {0,0,0});
Eigen::VectorXd vec2(30);
VectorXd::Map(&vec2[0], vec1.size()) = vec1;

(see eg https://stackoverflow.com/a/26094708/4069571 or https://stackoverflow.com/a/21560121/4069571 )

Also, it is possible to create an Eigen::Ref<VectorXd> from a Matrix block/column/... for example like

MatrixXd mat(10,10);
Eigen::Ref<VectorXd> vec = mat.col(0);

The Question

Is it possible to create an Eigen::Ref<VectorXd> from a std::vector<double> or even std::vector<Eigen::Vector3d> without first copying the data?

I tried and it actually works as I describe in my comment by first mapping and then wrapping it as a Eigen::Ref object. Shown here through a google test.

void processVector(Eigen::Ref<Eigen::VectorXd> refVec) {
  size_t size = refVec.size();
  ASSERT_TRUE(10 == size);
  std::cout << "Sum before change: " << refVec.sum(); // output is 50 = 10 * 5.0
  refVec(0) = 10.0; // for a sum of 55
  std::cout << "Sum after change: " << refVec.sum() << std::endl;
}

TEST(testEigenRef, onStdVector) {
  std::vector<double> v10(10, 5.0);
  Eigen::Map<Eigen::VectorXd> mPtr(&v10[0], 10);
  processVector(mPtr);
  // confirm that no copy is made and std::vector is changed as well
  std::cout << "Std vec[0]: " << v10[0] << std::endl; // output is 10.0
}

Made it a bit more elaborate after the 2nd edit. Now I have my google unit test for Eigen::Ref (thank you). Hope this helps.

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