How do I implement a CString hash function for use with std::unordered_map?(如何实现用于 std::unordered_map 的 CString 哈希函数?)
问题描述
我要声明:
std::unordered_map<CString, CString> m_mapMyMap;
但是当我构建时,我收到一个错误,告诉我标准 C++ 没有为 CString 提供哈希函数,而 CString 有 (LPCSTR) 运算符.
But when I build I got an error telling me that the standard C++ doesn't provide a hash function for CString, while CString have the (LPCSTR) operator.
如何正确实现 CString 的哈希函数?
How do I properly implement a hash function for CString?
推荐答案
基于 std::string 的 MS STL 实现,我创建了以下可用于 std 的方法::unordered_set 和 std::unordered_map:
Based on the MS STL implementation for std::string I created the following methods which can be used for std::unordered_set and std::unordered_map:
namespace std {
template <>
struct hash<CString>
{ // hash functor for CString
size_t operator()(const CString& _Keyval) const
{ // hash _Keyval to size_t value by pseudorandomizing transform
return (_Hash_seq((const unsigned char*)(LPCWSTR)_Keyval, _Keyval.GetLength() * sizeof(wchar_t)));
}
};
template <>
struct hash<CStringA>
{ // hash functor for CStringA
size_t operator()(const CStringA& _Keyval) const
{ // hash _Keyval to size_t value by pseudorandomizing transform
return (_Hash_seq((const unsigned char*)(LPCSTR)_Keyval, _Keyval.GetLength() * sizeof(char)));
}
};
}
或者更通用:
namespace std {
template<typename BaseType, class StringTraits>
struct hash<CStringT<BaseType, StringTraits>> : public unary_function<CStringT<BaseType, StringTraits>, size_t>
{ // hash functor for CStringT<BaseType, StringTraits>
typedef CStringT<BaseType, StringTraits> _Kty;
size_t operator()(const _Kty& _Keyval) const
{ // hash _Keyval to size_t value by pseudorandomizing transform
return (_Hash_seq((const unsigned char*)(StringTraits::PCXSTR)_Keyval,
_Keyval.GetLength() * sizeof(BaseType)));
}
};
}
这篇关于如何实现用于 std::unordered_map 的 CString 哈希函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何实现用于 std::unordered_map 的 CString 哈希函数?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
