Search code examples
c++eigeneigen3

Stl iterators with Eigen matrices


I have some functions that involves stl iterators and works with types like std::vector<Eigen::Vector2d>. For example:

template<typename T>
bool isLeftOf(const Eigen::Vector2<T>& a,
              const Eigen::Vector2<T>& b) {
  return (a.x() < b.x() || (a.x() == b.x() && a.y() < b.y()));
}

int main()
{
  std::vector<Eigen::Vector2i> myVec;
  myVec.push_back(Eigen::Vector2i::Random(2));
  myVec.push_back(Eigen::Vector2i::Random(2));
  myVec.push_back(Eigen::Vector2i::Random(2));
  myVec.push_back(Eigen::Vector2i::Random(2));
  myVec.push_back(Eigen::Vector2i::Random(2));
  
  Eigen::Vector2i element = *std::min_element(myVec.begin(), myVec.end(), isLeftOf<int>);

  return 0;
}

As you can see I create std::vector<Eigen::Vector2i> myVec and work with Eigen::Vector2<T> in function isLeftOf when calling std::min_element.

Now I'm experincing some troubles while working with std::vector<SomeEigenType> and I'm looking for a way to work with the same isLeftOf(Eigen::Vector2...) and stl functions but I don't understand how.

In Eigen documentation or in the forum there is some information how to perform stl operations on Eigen::Vector or Matrix but they work with plain numbers of matrix so I cant send Eigen::Vector2 to my isLeftOf function.

Is there a way to use stl functions with Eigen::Matrix and process condition in my functions like isLeftOf that accept Eigen::Vector types?


Solution

  • Using the master version of Eigen, you can use STL-like iterators which access rows or columns of matrices:

    Assuming myVec is a matrix you can write this to get the "left-most" column:

      Eigen::Vector2i element = *std::min_element(
          myVec.colwise().begin(), myVec.colwise().end(), 
          [](auto const& a, auto const& b){
              return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());
          });
    

    Godbolt-Demo: https://godbolt.org/z/n1Y8hf