Easy way to use containers with any data type

Revision en1, by Deepesson, 2022-07-26 04:19:39

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.

Let's say we want to use pair<int,int> with a 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 ints to use. Is there an easier way that is able to store any data structure?

Luckly there is!

We can use bitsets, and resize them for the size we want. 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;

That's the way we can use unordered_map, sets or similar data structures without coding hashes or comparators!

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)