-1

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;
Ali Akber Faiz
  • 117
  • 1
  • 12
  • 2
    You'll find a detaile description of the requirements for _`Key`_ types [here](https://en.cppreference.com/w/cpp/container/multimap). – πάντα ῥεῖ Dec 12 '20 at 13:28
  • 1
    A map is an ordered container, the ordering is based on the keys, so naturally they need to be compared to one another (using `operator<`). Also, don't prepend your type names with an underscore. – Mansoor Dec 12 '20 at 13:32
  • Thanks for your response, So i think it is better to look for some other solution then ? @M.A – Ali Akber Faiz Dec 12 '20 at 13:39

1 Answers1

2

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);