map<pair<int,int>,int>pairOfNumbers;
pairOfNumbers.insert(pair<pair<int,int>,int>({1,2},2));
这是有效的,但是
map<pair<point,point>,int>PointsOnLine;
PointsOnLine.insert(pair<pair<point,point>,int>(make_pair(points[i],points[j]),count));
这没有。
point 只是两个整数 x 和 y 的结构;
我不断收到错误'二进制表达式的无效操作数(常量点和常量点'这是点的结构。
struct point
{
int x;
int y;
public:
bool operator==(const point& p)
{
if(x==p.x && y==p.y)
return true;
else
return false;
}
bool operator!=(const point& p)
{
if(x==p.x &&y==p.y)
return false;
else
return true;
}
};
如何在 map 中插入两个点和它们之间的距离?
在 Xcode 我得到这个错误
最佳答案
您的 point
type 不支持弱排序。它没有确定 is-less-than 的方法。您可能认为您不需要它,因为您的 point
实际上隐藏在 std::pair<point,point>
中但你做了。std::pair<T1,T2>
仅当 T1
时才支持弱排序和 T2
做。在您的情况下,它们是同一类型,因此对于 std::pair<point,point>
用作 std::map<std::pair<point,pint>,T>
中的键, point
必须支持弱排序。
要支持弱排序,您必须提供 operator<
比较两个有问题的对象,或者比较器仿函数类型做同样的事情。您执行此操作的最简单方法是:
#include <tuple>
struct point
{
int x;
int y;
bool operator <(const point& p) const
{
return std::tie(x, y) < std::tie(p.x, p.y);
}
bool operator ==(const point& p) const
{
return !(*this < p || p < *this);
}
bool operator !=(const point& p) const
{
return *this < p || p < *this;
}
};
我冒昧地重新定义了
operator ==
和 operator !=
利用正确的operator <
的弱顺序属性.这不是必需的,但如果运算符(operator)根植于尽可能基本的代码,最终会更容易。通过上述更改,您应该可以同时使用 point
和 std::pair<point,point>
作为 std::map
中的键类型和 std::set
.事实上,严格的弱排序可以将所有基本比较器(<=、>、>=、!=、==)定义为来自 operator <
的派生。以一种或另一种形式(或相对于所做的事情)。我挑战你考虑它们,尝试实现它们,最重要的是,编写一些测试工具来验证你的实现。
关于c++ - 二进制表达式的无效操作数(常量点和常量点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61136933/