有这样的网站:
http://www.cplusplus.com/reference/unordered_map/unordered_map/
也就是说,可以为 std::unordered_map
的 Hash
和 Pred
参数提供函数指针,而不是类> 类模板。但是,没有示例,如果可能的话,我还没有设法使该功能起作用。非工作示例:
bool unordered_eq(const char* const s1, const char* const s2)
{
return !std::strcmp(s1, s2);
}
std::size_t unordered_hash(char const* s)
{
return std::hash<std::string>()(s);
}
std::unordered_map<char const*, std::string,
unordered_hash, unordered_eq> hashmap;
最佳答案
That say, one can provide a function pointer, instead of a class
不,那是误会。您可以向构造函数 提供函数指针而不是函数对象。模板参数仍然是一种类型——在本例中是函数指针的类型。所以,你必须写
typedef unordered_map<
char const*, string,
size_t(*)(char const*), // type for hashing
bool(*)(char const*, char const*) // type for equality
> yourmaptype;
yourmaptype hm (
4, // minimum number of buckets
&unordered_hash, // function address for hashing
&unordered_eq, // function address for equality
);
您的标准库为第一个参数定义了一个默认值,但此默认值并未标准化。似乎没有办法在保留 n 的特定于供应商的默认值的同时设置仿函数的值。我在这里使用 4 是相当随意的。
您应该考虑使用默认可构造的函数对象。这不仅可以让您在不指定最小存储桶大小的情况下逃脱,而且它还可能更快,因为仿函数对于编译器而言更更容易内联。
关于c++ - std::unordered_map 的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15334128/