Search code examples
c++multimap

Requirement for key in std::multimap


I have a std::multimap where key is a custom class. Something like this:

Class X {
public:
    std::string s;
    int x;
    operator <(const X& other) const { return s < other.s; }
};
std::multimap<X, int> mymap;

Now, I'd like to use upper_bound and lower_bound to iterate over all elements with the same value of "s". Do I need to implement some other operator for X (for example: ==). Or it will work properly just like this?

Also, what should I supply as argument for upper_bound and lower_bound? I assume I should create a dummy object with desired value of "s"?


Solution

  • Since class X is the key for the multimap, the parameter to upper_bound()/lower_bound() needs to be of that type. If class X has an implicit conversion from std::string (which is the type of X::s) then you can use that as the parameter to upper_bound()/lower_bound().

    The default comparison for multimap is less<> which simply calls operator <() - so that's the only operator you a required to have in class X for the multimap to work.