std :: unordered_map的函数指针

时间:2013-03-11 08:33:42

标签: c++ c++11 std

有类似这样的网站:

http://www.cplusplus.com/reference/unordered_map/unordered_map/

也就是说,可以为Hash类模板的Predstd::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;

1 个答案:

答案 0 :(得分: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
    );

您的标准库定义了第一个参数的默认值,但此默认值未标准化。似乎没有办法为n保留特定于供应商的默认值,同时设置仿函数的值。我在这里使用4是相当随意的。

您应该考虑使用default-constructible函数对象。这不仅可以让你在不指定最小桶大小的情况下逃脱,它也可能更快,因为仿函数很多更容易内联编译器。

相关问题