【问题标题】:Can multimaps be implemented with structures as key? If yes then how?可以用结构作为键来实现多图吗?如果是,那怎么办?
【发布时间】:2020-12-12 13:26:44
【问题描述】:

例如下面给出的点和正方形两种结构,如果可以的话,我如何插入新元素?

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

【问题讨论】:

  • 您将找到对 Key 类型 here 要求的详细说明。
  • 一个map是一个有序的容器,排序是基于key的,所以自然需要比较(使用operator&lt;)。另外,不要在你的类型名称前加上下划线。
  • 感谢您的回复,所以我认为最好寻找其他解决方案? @MA

标签: c++ multimap


【解决方案1】:

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

选项 1: 向 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: 向字典提供 Square 类型的排序。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    相关资源
    最近更新 更多