Reputation: 213
What am I trying to do is to turn map into unordered_map. I need this because the unordered map needs to be initialized at the very beginning, and in my case particular I can't do this, since I don't know the data in the beginning. So I've written a comparison function:
struct MapComparator
{
bool operator()( const string& a, const string& b ) const { return a != b; }
};
typedef std::map<string, SParamData, MapComparator> MapParamData;
The problem with this is that whenever I access field that is already used, instead of getting the values stored there, a new field with same name and default values is created and returned.
Upvotes: 0
Views: 6949
Reputation: 136515
I need this because the
unordered_map
needs to be initialized at the very beginning
std::unordered_map
has a default constructor, so that you can create an empty std::unordered_map
and populate it later.
Upvotes: 0
Reputation: 38209
Read documentation of std::map. Compare function describes LESS functionality not different.
Keys in std::map are ordered and order is described by comparator. So you need something like this (example of case insensitive key):
struct MapComparator
{
bool operator()( const string& a, const string& b ) const
{
return std::lexicographical_compare(
a.begin(), a.end(),
b.begin(), b.end(),
[](auto ch1, auto ch2) {
return std::tolower(ch1) < std::tolower(ch2);
});
}
};
typedef std::map<string, SParamData, MapComparator> MapParamData;
Note if two items are considered to be equal, hash function MUST return same hash value for this two items.
Upvotes: 2