c++ - std::unordered_map 的函数指针

标签 c++ c++11 std

有这样的网站:

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

也就是说,可以为 std::unordered_mapHashPred 参数提供函数指针,而不是类> 类模板。但是,没有示例,如果可能的话,我还没有设法使该功能起作用。非工作示例:

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/

相关文章:

c++11 - 避免函数调用时缩小类型转换

C++:使用指向 vector 开头的指针访问 vector 元素

c++ - Float OR Int 范围内的随机数

c++ - EOF - scanf 和 printf

pointers - 地址常量表达式

c++ - 在 C++ 上迭代 ini 文件,可能使用 boost::property_tree::ptree?

c++ - 在没有原始循环的情况下累积相等的范围

c++ - 防止使用第三方基类

c++ - Windows 通用应用程序 (XAML) : textBlock->Text cannot be called with the given argument list

c++ - 修改对作为参数传递给方法的 const char* 的引用是否有意义?