有像这样的网站:
http://www.cplusplus.com/reference/unordered_map/unordered_map/
这就是说,一个可以提供一个函数指针,而不是一类,对于Hash与Pred该参数的std::unordered_map类模板.但是,没有示例,如果可能的话,我还没有设法让这个功能起作用.非工作的例子:
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;
Run Code Online (Sandbox Code Playgroud)
sel*_*tze 10
也就是说,可以提供函数指针而不是类
不,这是一个误解.你可以提供一个函数指针,而不是一个函数对象的构造函数.模板参数仍然是一种类型 - 在这种情况下是函数指针的类型.所以,你必须写
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
);
Run Code Online (Sandbox Code Playgroud)
标准库定义了第一个参数的默认值,但此默认值未标准化.似乎没有办法为n保留特定于供应商的默认值,同时设置仿函数的值.我在这里使用4是相当随意的.
您应该考虑使用default-constructible函数对象.这不仅可以让你在不指定最小桶大小的情况下逃脱,它也可能更快,因为仿函数更容易内联编译器.