multitaskPro
multitaskPro

Reputation: 571

Custom equality compartor in unordered_map with initialization parameters

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.

Upvotes: 1

Views: 60

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117841

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

Upvotes: 1

Related Questions