为CString创建unordered_map作为键

4
我尝试创建以下unordered_map:
std::unordered_map<CString, CString, std::function<size_t(const CString &data)>> usetResponse(100, [](const CString &data)
    {
        return std::hash<std::string>()((LPCSTR)data);
    });

我为CString提供了哈希函数,但编译器仍然返回错误:
error C2338: The C++ Standard doesn't provide a hash for this type. 

error C2664: 'std::unordered_map<CString,CString,std::hash<_Kty>,std::equal_to<_Kty>,std::allocator<std::pair<const
_Kty,_Ty>>>::unordered_map(std::initializer_list<std::pair<const _Kty,_Ty>>,unsigned int,const std::hash<_Kty> &,const _Keyeq &,const std::allocator<std::pair<const _Kty,_Ty>> &)' : cannot convert argument 1 from 'std::unordered_map<CString,CString,std::function<size_t (const CString &)>,std::equal_to<_Kty>,std::allocator<std::pair<const
_Kty,_Ty>>>' to 'const std::unordered_map<CString,CString,std::hash<_Kty>,std::equal_to<_Kty>,std::allocator<std::pair<const
_Kty,_Ty>>> &'

请告诉我我做错了什么?


如果传递一个非lambda哈希函数会发生什么?会出现相同的错误吗? - Gillespie
请编辑您的问题,加入 [mcve]。 - Slava
仔细阅读错误信息:“*无法将参数1从'std :: unordered_map <CString,CString,std :: function <size_t(const CString&)>,...>'转换为'const std :: unordered_map <CString,CString,std :: hash <_Kty>,...>& *“。这意味着您正在尝试将自定义unordered_map类型的实例传递给使用标准unordered_map类型的函数参数。模板参数是类类型的一部分,因此您不能混合使用不同模板参数的类型。您需要编写std :: hash <CString>的专门化,而不是使用自定义哈希作为模板参数。 - Remy Lebeau
有没有不使用CMapStringToString的理由?https://msdn.microsoft.com/zh-cn/library/ddw782e0.aspx - Flaviu_
这个对象需要被函数返回,但是MFC容器没有默认的复制构造函数。在这种情况下,我不想为此创建包装器。 - drewpol
1个回答

5

类似这样的:

struct CStringHash
{
    size_t operator () (const CString &s) const
    {
        return hash<string>()(static_cast<LPCSTR>(s));
    }
};

然后这样声明地图:

unordered_map<CString, CString, CStringHash> map;

这个哈希函数存在缺陷,因为它基于CString内存地址而不是CString内容生成哈希值,因此您将无法根据CString值访问正确的元素。只有在使用相同的CString实例访问unordered_map中的值时才有效。 - Tomasz
1
哈希模板被设置为使用std :: string,该字符串从指针初始化。指针不用于生成哈希值。 - Sid S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接