繁体   English   中英

C ++ unordered_map问题

[英]C++ unordered_map problem

这次,我可以显示完整的代码:

#include <unordered_map>
#include <iostream>
#include <stdlib.h>

using namespace std;

bool mystrcmp(const char *s1, const char *s2) {
        int i = 0;
        do {
                if(s1[i] != s2[i])
                        return false;
        } while(s1[i++] != '\0');
        return true;
}

struct eqstr
{
  bool operator()(const char* s1, const char* s2) const
  {
    return mystrcmp(s1, s2);
  }
};


int main(void) {
    char buffer[5] = {'h', 'e', 'd', 'e', '\0'};
    unordered_map<char *, int , hash<char *> , eqstr> int_from_symbols;
    int_from_symbols["hede"] = 1;
    int_from_symbols["hodo"] = 2;
    unordered_map<char *, int , hash<char *> , eqstr>::const_iterator it = int_from_symbols.find(buffer);
    eqstr myeq;
    if(myeq("hede",buffer))
        fprintf(stderr, "no problem here\n");
    if(it == int_from_symbols.end())
        fprintf(stderr, "dammit\n");
    else fprintf(stderr, "%d\n", int_from_symbols[buffer]);
    return 0;
}

输出:

no problem here
dammit

知道发生了什么吗?

提前致谢,,
厄尼尔

问题是hash<char *>不能满足您的要求。 它不是专门对“字符串”进行散列的专用工具,而只是将指针作为散列返回。

将其添加到您的代码中,它将开始工作(尽管散列函数不是生产质量,仅用于演示):

namespace std
{
    template<>
    struct hash<char *> : public std::unary_function<char *, size_t>
    {
        size_t operator()(char* str) const
        { 
            size_t h = 0;
            for (; *str; ++str)
                h += *str;
            return h;
        }
    };
}

这里有一些关于“ char *”的哈希函数算法的综述:

http://www.cse.yorku.ca/~oz/hash.html

正如评论作者所言,上述提及的ASCII码总和并不是最好的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM