How to use unordered_map/set/whatever without hashes/comparators

Revision en7, by Deepesson, 2023-06-18 19:49:02

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 :)

Tags c++, hashmap, container, pointer

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en7 English Deepesson 2023-06-18 19:49:02 0 (published)
en6 English Deepesson 2023-06-18 19:48:51 56
en5 English Deepesson 2023-06-18 19:47:26 24 Tiny change: '**Too bored creating ' -> '**Are you tired of creating '
en4 English Deepesson 2023-06-18 15:34:29 143
en3 English Deepesson 2023-06-18 15:30:55 421 Tiny change: 'example:\n```cpp\ntypedef ' -> 'example:\n\n```\ntypedef '
en2 English Deepesson 2022-07-26 04:22:33 21 Tiny change: 'do:\n\n```cpp\ntyped' -> 'do:\n\n```\ncpp\ntyped'
en1 English Deepesson 2022-07-26 04:19:39 1328 Initial revision (saved to drafts)