If you use Eigen library and C++11 a lot, especially `std::unordered_map`

, you may want to use matrix or vector of Eigen library as key. I encountered this case when I implemented spatial hashing that boosts the performance of collision detection. It requires a hash table that maps integer indices (i, j, k) to a list of vertices and faces in the cell. I picked `Eigen::Vec3i`

type to store three integer indices because it makes other computations easy. Here is the declaration of the unordered map I used.

/* Index of cell -> vertices in the cell. */ unordered_map<Vec3i, vector::<Vertex*>, matrix_hash<Vec3i>> spatial_hashing;

As you can see, I needed to find out what hash function would be good for three ordered integers first to use `std::unordered_map`

as my hash table implementation. I googled it and found several solutions. Among them I’m going to show you one that I think most versatile because you can apply it to Eigen matrix and vector of any length, not only one-by-three. Here is the definition of the hash function `matrix_hash`

, and please let me know if you think there is a better solution!

// Hash function for Eigen matrix and vector. // The code is from `hash_combine` function of the Boost library. See // http://www.boost.org/doc/libs/1_55_0/doc/html/hash/reference.html#boost.hash_combine . template<typename T> struct matrix_hash : std::unary_function<T, size_t> { std::size_t operator()(T const& matrix) const { // Note that it is oblivious to the storage order of Eigen matrix (column- or // row-major). It will give you the same hash value for two different matrices if they // are the transpose of each other in different storage order. size_t seed = 0; for (size_t i = 0; i < matrix.size(); ++i) { auto elem = *(matrix.data() + i); seed ^= std::hash<typename T::Scalar>()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } return seed; } };