开发者

C++ unordered_map problem

开发者 https://www.devze.com 2022-12-15 00:12 出处:网络
This time I\'m able to show a complete code: #include <unordered_map> #include <iostream> #include <stdlib.h>

This time I'm able to show a complete code:

#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>::cons开发者_如何学运维t_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;
}

This outputs:

no problem here
dammit

Any idea what's going on?

Thanks in advance,,

Onur


The problem is that hash<char *> does not do what you want. It is not specialized to actually hash the 'string' but is simply returning the pointer as the hash.

Add this to your code and it will start working (although the hash function is not production quality and is for demonstration only):

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;
        }
    };
}


a review of a few hash function algoirthms for 'char *' here:

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

the sum of ascii codes mentioned above is not the best as the author of the comment says.

0

精彩评论

暂无评论...
验证码 换一张
取 消