简体   繁体   中英

C++ unordered_map problem

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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