Using std::map with Eigen 3

3.1k views Asked by At

For efficiency purposes I need to write a code that takes a vector of integers as defined in Eigen 3, VectorXi, and maps that vector to a character. Like a dictionary in Python. How can I do this? The Eigen documentation does things the other way around (see below) - it maps a character to a vector. I can't get it to work in reverse. Has anyone ever tried this before?

std::map<char,VectorXi, std::less<char>,
     Eigen::aligned_allocator<std::pair<char, VectorXi> > > poop;

VectorXi check(modes);
check << 0,2,0,0;
poop['a']=check;
cout << poop['a'];
1

There are 1 answers

2
davidhigh On

Your code is trying to approach the solution from the completely opposite side. There, you construct a map in which the keys are of type char and the values are Eigen vectors.

Note further that according to the Eigen homepage custom allocators are only required for the fixed-size versions of Eigen types.

In order to use a std::map with a Eigen vector as key, you need an appropriate comparison function. For this, you can specialize std::less which is allowed for custom types. Here is a possible implementation:

namespace std
{
     template<>
     std::less<Eigen::VectorXi>(Eigen::VectorXi const& a, Eigen::VectorXi const& b)
     {
          assert(a.size()==b.size());
          for(size_t i=0;i<a.size();++i)
          {
               if(a[i]<b[i]) return true;
               if(a[i]>b[i]) return false;
          }
          return false;
     }
}

Then you should be able to write

std::map<VectorXi, char> poop;

VectorXi check;
check << 0,2,0,0;
poop[check]='a';
cout << poop[check];  //prints 'a'

The code above is untested, however.