【问题标题】:custom type inside map argument [duplicate]地图参数中的自定义类型[重复]
【发布时间】:2013-10-17 10:10:38
【问题描述】:

我偶然发现了一个我无法解决的关于地图的问题。众所周知,地图需要它要处理的两种类型的变量,即地图,但是自定义类型呢?

假设我有一个名为“Point”的对象,它包含两个变量 x 和 y。声明这样的地图是否可行:地图?请看下面的代码

class Point
{
public:
double x;
double y;
Point(double x, double y)
{
    this->x=x;
    this->y=y;
}
};

int main(int argc, const char * argv[])
{
      map<Point,int> myMap;
      Point p1(0,0);
      myMap[p1]=1;
} 

我收到一个编译错误:'二进制表达式的操作数无效('const Point' 和 'const Point')。

有谁知道为什么会这样,我该如何解决?任何帮助将不胜感激:)。

干杯!

【问题讨论】:

    标签: c++ map custom-type


    【解决方案1】:

    您需要为Point 提供operator&lt;。 std::map 内部调用operator&lt; 对键进行排序。

    bool operator<(const Point& lhs, const Point& rhs) 
    {
        // compares lhs.x to rhs.x,
        // then lhs.y to rhs.y
        return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
    }
    

    map,它从模板参数中获取Compare函数,std::less&lt;key&gt;是默认值。

    std::map 是一个排序的关联容器,其中包含具有唯一键的键值对。 使用比较函数比较对键进行排序。搜索、删除和插入操作具有对数复杂性。地图通常实现为红黑树

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-21
      • 2023-03-29
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多