I’d like to be able to do this:
std::unordered_map<icu::UnicodeString, icu::UnicodeString> mymap;
However, when I do (and I come to use it) I was getting “cannot convert size_t to UnicodeString” errors. So I had a look around and read up on unordered containers. This blog post makes the point that I need to make available a specialisation of std::hash<icu::UnicodeString>, so I did exactly that:
namespace std
{
template<>
class hash<icu::UnicodeString> {
public:
size_t operator()(const icu::UnicodeString &s) const
{
return (size_t) s.hashCode();
}
};
};
Not perfect, however, it satisfies the requirements. However, now I’m getting errors that stem from:
error C2039: 'difference_type' : is not a member of 'icu_48::UnicodeString'
The blog post itself hints that I need to be doing more; however, it doesn’t tell me what I should do, ending on these remarks:
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.
So, now I’m a little confused, because operator== is defined for UnicodeString.
So, using C++11, MSVC and GCC. Also compiling with Qt dependencies. Then, my question is, what more do I need to do in order to add icu::UnicodeString types to an unordered map?
As requested, I’m later attempting to iterate over the map. The map itself is part of a class, called 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...
}
As OP discovered,
Since an unordered map has a 2-argument insert method,
the compiler will try to match the
keyas aconst_iterator, which is probably why thedifference_typetype member is requested (it is a member of an iterator).The correct way to insert an entry is to insert a pair,
or just use the “emplace” method,