gpt4 book ai didi

c++ - 如何使用非 STL 类型(例如来自 ICU 的 UnicodeString)创建 unordered_map?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:04:47 27 4
gpt4 key购买 nike

我希望能够做到这一点:

std::unordered_map<icu::UnicodeString, icu::UnicodeString> mymap;

但是,当我这样做(并且开始使用它)时,我遇到了“无法将 size_t 转换为 UnicodeString”的错误。所以我环顾四周,read up on unordered containers .这篇博文指出我需要提供 std::hash<icu::UnicodeString> 的特化,所以我就是这么做的:

namespace std
{
template<>
class hash<icu::UnicodeString> {
public:
size_t operator()(const icu::UnicodeString &s) const
{
return (size_t) s.hashCode();
}
};
};

虽然不完美,但满足要求。但是,现在我收到以下错误:

error C2039: 'difference_type' : is not a member of 'icu_48::UnicodeString'

博文本身暗示我需要做更多;然而,它并没有告诉我我应该做什么,以这些评论结束:

In addition to requiring a hash function, the unordered containers also need to be able to test two keys for equality. The canonical way for them to do this is with a version of operator==() defined at the global namespace. This is typically a function you are used to having to construct when creating new classes, but if you overlook it, you will be up against the same raft of incomprehensible compiler errors seen earlier in this article.

I didn’t have to deal with it in this article because the standard library already defines this operator for std::pair. Of course, when using std::pair you also have to make sure you have an equality operator for T1 and T2.

所以,现在我有点困惑,因为 operator== is defined for UnicodeString .

因此,使用 C++11、MSVC 和 GCC。还使用 Qt 依赖项进行编译。然后,我的问题是,我还需要做什么才能添加 icu::UnicodeString类型到无序映射?

根据要求,我稍后会尝试遍历 map 。 map 本身是类的一部分,称为 this->mymap :

std::unordered_map<icu::UnicodeString, icu::UnicodeString>::const_iterator it;
for ( it = this->mymap.begin(); it != this->mymap.end(); ++it )
{
// access it->first, it->second etc...
}

最佳答案

正如 OP 所发现的,

somebody had left a nice mymap->insert(key, value) which is wrong wrong wrong

由于无序映射有一个 2 参数插入方法,

template <class P>
iterator insert(const_iterator hint, P&& obj);

编译器会尝试将 key 作为 const_iterator 进行匹配,这可能就是请求 difference_type 类型成员的原因(它是一个迭代器的成员)。

插入条目的正确方法是插入一对,

mymap.insert(std::make_pair(key, value));

或者只使用“emplace”方法,

mymap.emplace(key, value);

关于c++ - 如何使用非 STL 类型(例如来自 ICU 的 UnicodeString)创建 unordered_map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10125211/

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