Std::map comparison function

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

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

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

Marek R
Marek R

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;


Since C++11 new container has been introduced. It is std::unordered_map. In this container keys do not have defined any specific key order. It uses hash function to speed up match. In this case when you need custom key matching you have to provide two functions:

  • a hash function
  • a equal function

Note if two items are considered to be equal, hash function MUST return same hash value for this two items.

Upvotes: 2

Related Questions