PThomasCS PThomasCS - 1 month ago 17
C++ Question

Extending Eigen Library to Include Sorting

I would like to extend the C++ Eigen library to include a command v.sort(); I'm using the EIGEN_MATRIXBASE_PLUGIN based approach outlined here.

The code below (in my "MatrixBaseAddons.h") does not work, because the "result" object does not get loaded with a copy of "this"---in the debugger, "result.rows()" is an uninitialized value not equal to derived()->rows(). How do I actually make a copy of "this" and put it in "result"?

// DOES NOT WORK
MatrixBase<Derived> sort(bool ascending = true) const {
MatrixBase<Derived> result = derived();
result.sortInPlace(ascending);
return result;
}

// WORKS!
void sortInPlace(bool ascending = true) {
std::sort(derived().data(), derived().data() + derived().size());
if (!ascending)
this->reverseInPlace();
}

Answer

MatrixBase is an abstract class. You need to return a Matrix<> object with appropriate scalar type and sizes. You can directly use the typedef PlainObject for that:

PlainObject sort(bool ascending = true) const {
  PlainObject res = derived();
  ...
  return res;
}
Comments