Deepesson's blog

By Deepesson, history, 21 month(s) ago, In English

Are you tired of creating comparators or hashes for your custom class? I have a solution for you.

Sometimes we need to use STL data structures such as map, unordered_map or set using a data type that doesn't have a hash or a comparator. Instead of coding things properly I will show an easy way to achieve the same thing with minimal effort.

The idea is to use pointer casting.

Let's say we want to use pair<int,int> with an unordered_map (notice that there's no pre-made hash for this data type).

The size of pair<int,int> is 8 bytes. Also notice that we have long long: a data type also 8 bytes long.

We can create an unordered_map, and to check our pair we can just do:

typedef std::pair<int,int> pii;
std::unordered_map<long long,int> hashmap;
pii object;
hashmap[*((long long*)&object)] = 24;

We can recast our data type for another data type of the same size, and it will work just fine! But we don't have endless integers to use. Is there an easier way that is able to store any data structure?

Luckily there is!

We can use bitsets, and resize them as we wish. Following our previous example:

typedef std::pair<int,int> pii;
typedef std::bitset<sizeof(pii)*8> bits;
std::unordered_map<bits,int> hashmap;
pii object;
hashmap[*((bits*)&object)] = 24;

Here we create a bitset exactly the size of our class, making us able to use any standard container with our pair<int,int>.

Reason for this blog: I have used this trick for a somewhat long time, but it seems that not many programmers are aware of this method (+ I didn't find anything talking about this technique), so here it is :)

Full text and comments »

  • Vote: I like it
  • +172
  • Vote: I do not like it