Quick and dirty Eigen Matrix/Vector as std::map key

Alec Jacobson

April 28, 2015

weblog/

I tried to use an Eigen matrix type as the key to a std::map with something like:

std::map<Eigen::VectorXd,bool> m;

But got compile-time errors of the sort:

error: no viable conversion from 'const CwiseBinaryOp<std::less<Scalar>, const Eigen::Array<double, -1, 1, 0, -1, 1>, const Eigen::Array<double, -1, 1, 0, -1, 1> >' to 'bool'
    {return __x < __y;}
            ^~~~~~~~~

Seems that map wants a proper less than operator and Eigen has overloaded that with the coefficient-wise operator. A reasonable way to sort vectors would be lexicographically. Fortunately stl has a function for that, so I define my map like this:

std::map<
  Eigen::VectorXd,
  bool,
  std::function<bool(const Eigen::VectorXd&,const Eigen::VectorXd&)> >
  m([](const VectorXd & a, const VectorXd & b)->bool
  {
    return std::lexicographical_compare(
      a.data(),a.data()+a.size(),
      b.data(),b.data()+b.size());
  });

This will ignore the internal ordering of the matrix elements (i.e. ColMajor vs RowMajor) but if you're just using the map for a uniqueness check this is good enough.