gpt4 book ai didi

c++ - 非库类型的无序 key_type 需要 hash<> 特化?

转载 作者:行者123 更新时间:2023-11-28 03:27:42 25 4
gpt4 key购买 nike

我正在尝试创建一个以 xercesc::XMLUri 作为键类型的 std::unordered_map。

#include <unordered_map>
#include "xercesc/util/XMLUri.hpp"

int main()
{
std::unordered_map<xercesc::XMLUri,xercesc::XMLUri> uriMap;
}

结果如下:

clang++ -std=c++11 -O0 -emit-llvm -g3 -Wall -c -fmessage-length=0 -I/usr/include ../xx.cpp 
In file included from ../xx.cpp:1:
In file included from /usr/bin/../lib/gcc/i686-linux-gnu/4.7/../../../../include/c++/4.7/unordered_map:43:
/usr/bin/../lib/gcc/i686-linux-gnu/4.7/../../../../include/c++/4.7/bits/functional_hash.h:59:7: error: static_assert failed "std::hash is not specialized for this type"
static_assert(sizeof(_Tp) < 0,
^ ~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/i686-linux-gnu/4.7/../../../../include/c++/4.7/bits/unordered_map.h:45:32: note: in instantiation of template class 'std::hash<xercesc_3_1::XMLUri>' requested here
integral_constant<bool, !__is_final(_Hash)>,
^
/usr/bin/../lib/gcc/i686-linux-gnu/4.7/../../../../include/c++/4.7/bits/unordered_map.h:263:14: note: in instantiation of default argument for '__unordered_map<xercesc_3_1::XMLUri, xercesc_3_1::XMLUri, std::hash<xercesc_3_1::XMLUri>, std::equal_to<xercesc_3_1::XMLUri>, std::allocator<std::pair<const xercesc_3_1::XMLUri, xercesc_3_1::XMLUri> > >' required here
: public __unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../xx.cpp:6:54: note: in instantiation of template class 'std::unordered_map<xercesc_3_1::XMLUri, xercesc_3_1::XMLUri, std::hash<xercesc_3_1::XMLUri>, std::equal_to<xercesc_3_1::XMLUri>, std::allocator<std::pair<const xercesc_3_1::XMLUri, xercesc_3_1::XMLUri> > >' requested here
std::unordered_map<xercesc::XMLUri,xercesc::XMLUri> uriMap;

我知道 C++0x 中的无序容器只提供 hash<>某些库类型的特化。如何创建所需的 hash<xercesc::XMLUri>特化xercesc::XMLUri

编辑:我想到了这个。看起来合理吗?

#include "xercesc\util\XMLUri.hpp"
#include <string>

namespace std
{

size_t hash<xercesc::XMLUri>::operator()(const xercesc::XMLUri& uri) const
{
return hash<std::wstring>()(uri.getUriText());
}
}

最佳答案

差不多。它应该是这样的(感谢@jogojapan 指出缺少的类型定义!):

#include <string>
#include <functional>

namespace std
{
template <> struct hash<xercesc::XMLUri>
{
typedef size_t result_type;
typedef xercesc::XMLUri argument_type;

size_t operator()(xercesc::XMLUri const & uri) const noexcept
{
return hash<wstring>()(uri.getUriText());
}
};
}

关于c++ - 非库类型的无序 key_type 需要 hash<> 特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13503773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com