简体   繁体   English

C++ 如何使用带有自定义 hash 的 unordered_map 并将这些函数作为成员变量进行比较,如果这些函数在构造函数中传递?

[英]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

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?如何在我的unordered_map中使用 function 指针,但仍将 map 作为成员变量? Because at the time when I get these function pointers in the Constructor, the map is already created.因为当我在构造函数中获得这些 function 指针时,已经创建了 map。

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.考虑到您已经用 C++14 标记了 Q,我将使用std::function而不是 function 指针发布我的答案。 You can write your class C like this:你可以这样写你的 class C

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.然后使用所需的参数实例化您的 class 。 See the live demo here.在此处查看现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在C ++中,对于unordered_map / set是否有更快的哈希函数? - Are there faster hash functions for unordered_map/set in C++? C++:扩展已创建的 C 结构与自定义 hash 和可在 unordered_map 中使用的相等功能 - C++: Extend already created C struct with custom hash and equal functions to be usable in unordered_map Unordered_map 的 Unordered_map 与自定义 hash function 的配对密钥 C++? - Unordered_map of unordered_map vs custom hash function for pair key C++? C++ 11 将自定义 hash function 传递到 unordered_map - C++ 11 passing custom hash function into unordered_map std::unordered_map 如何实际使用 hash 函数? - How does std::unordered_map actually use hash functions? C++:如何使用指向函数的指针值创建成员 unordered_map - C++: How to create a member unordered_map with values of pointers to functions unordered_map哈希函数c ++ - unordered_map hash function c++ 我怎样才能避免在 C++ 中对 const unordered_map 使用“[]”运算符? - How can I get around from using "[]" operator on const unordered_map in C++? 如何在c ++中使用unordered_map的unordered_map? - How to use unordered_map of unordered_maps in c++? C ++哈希表-如何解决自定义数据类型作为键的unordered_map的冲突? - C++ Hash Table - How is collision for unordered_map with custom data type as keys resolved?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM