gpt4 book ai didi

c++ - 具有自定义哈希函数 (_bstr_t) 的无序映射仅适用于默认构造函数(重复键)

转载 作者:行者123 更新时间:2023-11-30 02:54:04 34 4
gpt4 key购买 nike

我有一个键类型为 _bstr_t 的无序映射。因此,由于哈希函数默认不支持这种键类型,因此我定义了仿函数:

struct KeyHash {
size_t operator()(const _bstr_t& key) const {
return hash<LPCTSTR>()(key);
}
};

接下来我定义了 typedef:

typedef unordered_map<_bstr_t, RecentInfo*, KeyHash> RecentInfoMap;

然后出现问题:如果我用默认构造函数实例化 RecentInfoMap

RecentMapInfo rim;

然后一切正常。但是如果我想用初始桶数实例化 RecentInfoMap

RecentInfoMap rim(100);

然后 map 不工作。我无法通过它的键获取值。此外,如果我在使用 map 之前调用 rim.rehash(100),那么也无法正常工作。

请解释我做错了什么。

更新:一些代码示例:

unordered_map<bstr_t, int, KeyHash> map;
_bstr_t t1("ORCL");
_bstr_t t2("ORCL");
map[t1] = 777;
map[t2] = 555;
fout << map[t1] << endl;
fout << map[t2] << endl;

一切正常:map[t1] 和 map[t2] 引用一个值 555。但是如果 map 定义为

 unordered_map<bstr_t, int, KeyHash> map(100);

然后出现错误:map 包含重复键和 map[t1] 对 777 的引用以及 map[t2] 对 555 的引用。

此语句(使用 rehash 调用)也提供重复键:

unordered_map<bstr_t, int, KeyHash> map;
map.rehash(100);

最佳答案

我找到了解决方案。刚刚编写了我自己的自定义哈希函数,它可以使用 char* (wchar_t*) 指针。还添加了相等仿函数。对我来说很好用。希望它对某人有用。

struct KeyHash {
size_t operator()(const _bstr_t& key) const {
LPCTSTR str = key;
LPCTSTR end = str + _tcslen(str);
size_t hash = 2166136261U;
while (str != end) {
hash = 16777619U * hash ^ static_cast<size_t>(*str++);
}
return hash;
}
};


struct KeyEquals {
bool operator()(const _bstr_t& x, const _bstr_t& y) const {
return _tcscmp(x, y) == 0;
}
};


typedef unordered_map<_bstr_t, RecentInfo*, KeyHash, KeyEquals> RecentInfoMap;

关于c++ - 具有自定义哈希函数 (_bstr_t) 的无序映射仅适用于默认构造函数(重复键),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17365915/

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