我偶然发现了一个关于 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/