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 哈希函数?
- STL 中有 dereference_iterator 吗? 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
