c++ - 具有自定义散列/相等函数的 unordered_map - 函数不会被调用

标签 c++ c++11

<分区>

这很奇怪.. 下面的代码(我设法通过 Cassio Neri 编译)编译没有任何错误.. 顺便说一下,hashing_func 和 key_equal_func 都被调用了(couts 没有显示在控制台中)窗口)

#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <functional>

using namespace std;

unsigned long hashing_func(string key)
{
    cout << "Hashing called";
    unsigned long hash = 0;
    for(int i=0; i<key.size(); i++)
    {
        hash += (71*hash + key[i]) % 5;
    }
    return hash;
}

template<class T> bool key_equal_fn(T t1, T t2)
{
    return t1 == t2;
}

template <> bool key_equal_fn<string>(string t1, string t2)
{
    cout << "Equal called";
    return !(t1.compare(t2));
}

int main ()
{
    unordered_map<string, string>::size_type n = 5;
    unordered_map<string, string> mymap(n, (const std::hash<string> &)hashing_func, 
        (const std::equal_to<string> &)(function<bool(string,string)>(key_equal_fn<string>))) ;

    bool case_insensitive = mymap.key_eq()("test","TEST");

    mymap["paul"] = "jenna";
    mymap["frank"] = "ashley";

    if(mymap["paul"] == mymap["frank"])
        cout << "equal" << endl;


    return 0;
}

我正在使用 MSVC2012,有什么问题可以提示吗?

最佳答案

您必须使用模板参数指定散列/比较函数,而不是在构造函数中。这是一个例子:

class Hasher
{
public:
  size_t operator() (string const& key) const
  {
      cout << "Hashing called";
      size_t hash = 0;
      for(size_t i=0; i<key.size(); i++)
      {
          hash += (71*hash + key[i]) % 5;
      }
      return hash;
  }
};
class EqualFn
{
public:
  bool operator() (string const& t1, string const& t2) const
  {
    cout << "Equal called";
    return !(t1.compare(t2));
  }
};

unordered_map<string, string, Hasher, EqualFn> mymap(5);

关于c++ - 具有自定义散列/相等函数的 unordered_map - 函数不会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15810620/

相关文章:

c++ - Stringstream清零麻烦

c++ - 在不同类型之间转换 const 指针

c++ - 如何正确使用 C++ 强类型枚举?

c++ - 用于检测模板函数的 Sfinae 类型特征不适用于 std::forward

c++ - C++中的运算符重载

c++ - map::const_iterator 映射类型不是 const

c++ - 在 C++ 中声明泛型 istream

c++ - while 循环跳过所有其他输入

c++ - 错误读取变量 : Could not find the frame base

c++ - 无法在 OpenGL 上使用不同的 VAO 渲染不同的网格