mercredi 20 décembre 2017

std::unordered_set vs std::unordered_map trade-offs

A lot of times I see my key is actually inside my value.
For example:

struct Elem {
    int key;
    // ... Other variables ...
}

That makes me want to use std::unordered_set instead of std::unordered_map, because I already have the key stored inside my value - no need to waste more place for std::unordered_map's .first (key).

Then I start implementing with std::unordered_set and get to the place I need to perform a find() over my std::unordered_set.
Then I realize I need to create an empty-shell Elem so I would be able to find(), beacuse std::unordered_set::find gets a Key for input

template < class Key,                    // unordered_set::key_type/value_type
       class Hash = hash<Key>,           // unordered_set::hasher
       class Pred = equal_to<Key>,       // unordered_set::key_equal
       class Alloc = allocator<Key>      // unordered_set::allocator_type
       > class unordered_set;

Sometimes building an empty-shell Elem is hard / wasteful / maybe even not possible?

For example, when my key/value is

  • An iterator
  • A reference
  • A class with specific c'tor (not constructing the instance only with the key)

Q. Am I missing something?
Q. Is there a way to do find() that isn't wasteful?

  • Something really strange to me - that I already should have the element I'm looking for in order to find it, or at least an empty-shell of it.

Aucun commentaire:

Enregistrer un commentaire