为什么 std::unordered_set 不将 CComBSTR 类型作为键?
Why does std::unordered_set not take CComBSTR type as a key?
当我尝试使用 std::unordered_set<CComBSTR>
(或 std::unordered_set<CAdapt<CComBSTR>>
)时,出现错误
c:\apps\vs2017pro\vc\tools\msvc.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)时间复杂度?(当然我们可以使用自定义的hash函数来达到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;
}
编辑(2019 年 6 月 2 日):
我理解 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;
}
当我尝试使用 std::unordered_set<CComBSTR>
(或 std::unordered_set<CAdapt<CComBSTR>>
)时,出现错误
c:\apps\vs2017pro\vc\tools\msvc.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)时间复杂度?(当然我们可以使用自定义的hash函数来达到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;
}
编辑(2019 年 6 月 2 日):
我理解 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;
}