提问者:小点点

MultiMap可以以结构为关键实现吗?如果是,那怎么做?


例如,下面给出的两种结构,如点和方,如果有可能的话,我该如何插入新元素呢?

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

共1个答案

匿名用户

是的,作为键的结构与作为键的类没有什么不同。您有两个选项可以让您的代码正常工作。

选项1:Supply ordering到Square类型。

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

选项2:向字典提供方形类型的排序。

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