当我尝试使用std::unordered_set<CComBSTR>
(或std::unordered_set<CAdapt<CComBSTR>>
)时,出现错误
c:\apps\vs2017pro\vc\tools\msvc\14.16.27023\include\unordered_set(105) : error C2280 : 'std::hash<_Kty>::hash(const std::hash<_Kty> &)' : attempting to reference a deleted function
with
[
_Kty = ATL::CComBSTR
]
但是
std::set<CComBSTR>
(或std::set<CAdapt<CComBSTR>>
)很好。我正在使用Visual Studio 2017。我该怎么做才能仍然达到O(1)的搜索时间复杂度? (当然,我们可以使用自定义哈希函数来实现O(1)时间复杂度的搜索。)
最小的可重现示例如下。
#include "atlbase.h"
#include <unordered_set>
#include <set>
int main()
{
//std::unordered_set<CComBSTR> s; // compile error
//std::unordered_set<CAdapt<CComBSTR>> s; // compile error
//std::set<CComBSTR> s; // ok
//std::set<CAdapt<CComBSTR>> s; // ok
return 0;
}
编辑(06/02/2019):
我知道
CComBSTR
没有哈希函数的错误,我们可以创建一个自定义函数。我要问的是std::set
具有哈希函数而不是std::unordered_set
的设计原因是什么? 最佳答案
这里的问题是编译器不知道如何散列密钥。要解决此问题,您需要提供一个自定义哈希函数:
#include "atlbase.h"
#include <unordered_set>
#include <set>
#include <string>
struct HashBSTR
{
size_t operator () (const CComBSTR &bstr)
{
return std::hash <std::wstring> () (bstr.m_str);
}
};
int main()
{
std::unordered_set <CComBSTR, HashBSTR> s;
return 0;
}
关于c++ - 为什么std::unordered_set不采用CComBSTR类型作为键?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56398921/