1

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'];
Jake Smith
  • 41
  • 2
  • 4
  • For starters, you probably want to use an unordered_map, unless you want to define a sort function for VectorXi. – user888379 Nov 20 '14 at 20:04

1 Answers1

2

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.

Community
  • 1
  • 1
davidhigh
  • 14,652
  • 2
  • 44
  • 75
  • Alright! This is exactly what I was looking for. My vectors are ordered lexicographically, so the inequalities will have to defined a little bit differently, but I got it from here. Thanks bra. – Jake Smith Nov 21 '14 at 17:25
  • Fine. But what I've written is lexicographic ordering imo. – davidhigh Nov 21 '14 at 20:54