Search code examples
c++multimap

Can multimaps be implemented with structures as key? If yes then how?


For example two structures like point and square as given below if it is possible to do so how may i insert new elements into it?

typedef struct _point{
int x;
int y;
}Point;
typedef struct _square{
float belowLeftX;
float belowLeftY;
}Square;
multimap <Square, Point > dictionary;

Solution

  • Yes, a structure as key is not different compared to a class as key. You have two options to get your code working.

    Option 1: Supply ordering to the Square type.

    typedef struct _square {
        float belowLeftX;
        float belowLeftY;
        bool operator<(struct _square const& rhs) const
        {
            if (belowLeftX < rhs.belowLeftX) return true;
            if (rhs.belowLeftX < belowLeftX) return false;
            return belowLeftY < rhs.belowLeftY;
        }
    

    Option 2: Supply ordering of the Square type to the dictionary.

    auto comparator = [](Square const& lhs, Square const& rhs)
    {
        if (lhs.belowLeftX < rhs.belowLeftX) return true;
        if (rhs.belowLeftX < lhs.belowLeftX) return false;
        return lhs.belowLeftY < rhs.belowLeftY;
    };
    
    std::multimap <Square, Point, decltype(comparator)> dictionary(comparator);