gpt4 book ai didi

C++ unordered_map问题

转载 作者:行者123 更新时间:2023-11-30 03:11:48 25 4
gpt4 key购买 nike

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

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

关于C++ unordered_map问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1960643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com