1

I am using std::unordered_map with a custom equality comparator class like so:

class KeyCompare {
private:
    HelperClass* helper;

public:
    KeyCompare(HelperClass* helper): helper(helper) {}
    
    bool operator()(const Key& key1, const Key& key2) const {
        return helper->doStuff(key1, key2);
    }
}

At some point in my code I initialize my map like this:

HelperClass helper;
std::unordered_map<Key, Value, Hasher, KeyCompare> map;

I would like to pass helper to the map such that KeyCompare objects are created with this helper. Is such a thing possible? I can use some global variable if absolutely necessary, but I would really like to avoid that.

multitaskPro
  • 569
  • 4
  • 14
  • 1
    Pass them in [`std::unordered_map`'s constructor](https://en.cppreference.com/w/cpp/container/unordered_map/unordered_map) – Jarod42 Nov 08 '21 at 15:27

1 Answers1

1

Since your KeyCompare needs a helper it isn't default constructible. You must therefore supply an instance to the unordered_map when you construct it.

Example:

HelperClass helper;

std::unordered_map<Key, Value, Hasher, KeyCompare> map{
    1,                   // bucket count
    Hasher{},            // hasher instance
    KeyCompare{&helper}  // your KeyCompare with the helper
};

Demo

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Question is then [which `bucket_count` to pass?](https://stackoverflow.com/questions/14179441/what-should-i-pass-to-unordered-maps-bucket-count-argument-if-i-just-want-to-sp). – Jarod42 Nov 08 '21 at 15:43
  • @Jarod42 Indeed. It seems passing any small number is usually ok? – Ted Lyngmo Nov 08 '21 at 15:47