c++ - map 参数内的自定义类型

标签 c++ dictionary custom-type

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

假设我有一个名为“Point”的对象,它由两个变量 x 和 y 组成。声明一个 map 是否可行:map?请看下面的代码

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’)。

有谁知道为什么会发生这种情况以及如何解决它?任何帮助将不胜感激:)。

干杯!

最佳答案

您需要提供operator<对于 Point 。 std::map 内部调用 operator<对键进行排序。

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<key>是默认值。

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

关于c++ - map 参数内的自定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19282398/

相关文章:

Python字典复制方法

java - 如何使用 Hibernate 映射用户数据类型(复合类型)

sql - 我可以使用自定义类型字段加入吗?

c++ - 将对数组的引用传递给返回数组引用的函数

引用的 C++ 变量范围

c++ - 当 const 在另一行时,Doxygen 错误地解析 const 成员函数

c++ - 如何随机化一个充满字符串的数组? C++

python - 如何将字典放入数据存储区?

python - 退格键似乎在 python 中不起作用

go - 自定义 UnmarshalYAML,如何在自定义类型上实现 Unmarshaler 接口(interface)