C++ 一个结构中多个点的运算符
我有一个结构,它存储两个应该可以互换的点C++ 一个结构中多个点的运算符,c++,algorithm,struct,operator-keyword,C++,Algorithm,Struct,Operator Keyword,我有一个结构,它存储两个应该可以互换的点 struct Edge { unsigned short firstIndex; unsigned short secondIndex; Edge(unsigned short firstIndex, unsigned short secondIndex) : firstIndex(firstIndex), secondIndex(secondIndex) {} }; 运算符==方法应如下所示(以使其可互换) 我
struct Edge
{
unsigned short firstIndex;
unsigned short secondIndex;
Edge(unsigned short firstIndex, unsigned short secondIndex) :
firstIndex(firstIndex), secondIndex(secondIndex) {}
};
运算符==
方法应如下所示(以使其可互换)
我希望创建一个操作符
方法,以便在std::map
中使用结构
我尝试了以下方法(使用乘法),但它不起作用,因为在许多情况下,不同的边返回相同的值
bool operator < (const Edge& e2) const
{
return first * second < e2.first * e2.second;
}
bool运算符<(常数边&e2)常数
{
返回first*second
我想使用的代码如下:
std::map<Edge, unsigned int> edgePoints;
Edge e1(0, 1);
Edge e2(1, 2);
Edge e3(2, 0);
edgePoints[e1] = 2;
edgePoints[e2] = 0;
edgePoints[e3] = 1;
std::地图边缘点;
边e1(0,1);
边缘e2(1,2);
边e3(2,0);
边点[e1]=2;
边点[e2]=0;
边点[e3]=1;
尽管代码不能与my
运算符一起使用,但请考虑将它们作为排序对进行比较
bool operator < (const Edge& e2) const
{
if (min(first, second) != min(e2.first, e2.second))
return min(first, second) < min(e2.first, e2.second);
return max(first, second) < max(e2.first, e2.second);
}
bool运算符<(常数边&e2)常数
{
if(min(第一,第二)!=min(e2.first,e2.second))
返回最小值(第一,第二)
编辑:当然,将mins和maxes保存为局部变量可以编写得更好,但是想法应该很清楚
编辑:另一个答案中的想法更好:强制您的结构始终使用第一个,而不是第二个,这样它将消除所有的分钟和最大值,并使比较运行得非常快)我将以这样一种方式存储边的索引,即较小的索引始终是第一个索引。看起来内部表示在应用程序中是不相关的。映射不需要操作符==
。以下是示例结构:
struct Edge
{
typedef unsigned short Idx; // prefer strong typedef cf boost
Edge(Idx a, Idx b)
:
firstIndex(std::min(a, b)),
secondIndex(std::max(a, b))
{}
Idx firstIndex;
Idx secondIndex;
bool operator<(Edge const & other)
{
if (firstIndex != other.firstIndex)
return firstIndex < other.firstIndex;
return secondIndex < other.secondIndex;
}
}; // Edge
struct-Edge
{
typedef unsigned short Idx;//首选强typedef cf boost
边缘(Idx a、Idx b)
:
第一索引(标准::最小(a,b)),
第二个索引(标准::最大值(a,b))
{}
Idx第一指数;
Idx二级指数;
bool操作符如果你为你的Edge
类型提供了一个看起来像我想要的hash函数,你可以使用unordered\u映射,尽管我的hash函数应该是什么?如果first操作符==
。而且你也不需要它来std::map
。旁注:std::tie(firstIndex,secondIndex)struct Edge
{
typedef unsigned short Idx; // prefer strong typedef cf boost
Edge(Idx a, Idx b)
:
firstIndex(std::min(a, b)),
secondIndex(std::max(a, b))
{}
Idx firstIndex;
Idx secondIndex;
bool operator<(Edge const & other)
{
if (firstIndex != other.firstIndex)
return firstIndex < other.firstIndex;
return secondIndex < other.secondIndex;
}
}; // Edge