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 哈希函数?


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30