-1

I have been given a mutlimap

typedef std::multimap<std::string, size_t, StringLenCmp> wordDictType;

in a class and I need to design a function that will insert a word and word length into the multi map. I know to traditionally insert into multimap, I would do

mmap["one"] = 1; 

or

mmap.insert(make_pair("one", 1)); 

but I don't know what StringLenCmp is. It is the class,

class StringLenCmp {

public:

    StringLenCmp() = default;

    // sort by length first, and then alphabetically
    bool operator()(const std::string& a, const std::string& b) const {
        return (a.size() < b.size()) || (a.size() == b.size() && a < b);
    }

private:
    // no data
};

but the problem is, I have no idea what all this means.

Can someone help me decipher all this.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
  • That third argument is what is used to order or sort the map. http://www.cplusplus.com/reference/map/multimap/ – Matt Nov 30 '18 at 21:19
  • I do not know which C++ compile you use, but the `operator []` is not available in g++ or the [std::multimap C++ reference](https://en.cppreference.com/w/cpp/container/multimap). – Alexis Wilke Oct 12 '22 at 03:13

2 Answers2

2

As you can read here, std::multimap is defined as

template < class Key,                                     // multimap::key_type
           class T,                                       // multimap::mapped_type
           class Compare = less<Key>,                     // multimap::key_compare
           class Alloc = allocator<pair<const Key,T> >    // multimap::allocator_type
           > class multimap;

The parameter class Compare is the part that is by default sorted based on the key value in ascending order (less<Key>) but you can define to do your custom sorting of elements in the map and your class StringLenCmp is doing exactly that. Each element is checked and sorted during insertion-time.

miller
  • 1,636
  • 3
  • 26
  • 55
2

It is a functor for the comparison function that "sorts" your multimap.

or simply a class that contains the operator overload such that it determines if any of the 2 elements is larger or smaller or equal to each other.

Koori
  • 61
  • 4