简体   繁体   中英

C++ How can I use an unordered_map with custom hash & compare as member variable if those functions get passed in Constructor?

Assume I have this class

class C {
private:
    std::unordered_map<struct MyStruct, int> map;
public:
    C(size_t(*hash)(const struct MyStruct &t1), bool(*comp)(const struct MyStruct &t1, const struct MyStruct &t2);
}

How can I use the function pointers in my unordered_map but still have the map as a member variable? Because at the time when I get these function pointers in the Constructor, the map is already created.

Considering the fact that you have tagged your Q with C++14, I will post my answer with std::function s instead of function pointers. You can write your class C like this:

using hash_t = std::function<size_t(const struct MyStruct &t1)>;
using comp_t = std::function<bool(const struct MyStruct &t1, const struct MyStruct &t2)>;

class C 
{
private:
   std::unordered_map<struct MyStruct, int, hash_t, comp_t> map;

public:
   C(int bucket_size, hash_t hasher, comp_t comper) :
      map(bucket_size, hasher, comper)
   {
   }
};

and then instantiate your class with the required parameters. See the live demo here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM