C++ STL在容器中存储无向图节点
我需要存储唯一的C++ STL在容器中存储无向图节点,c++,stl,containers,C++,Stl,Containers,我需要存储唯一的 struct Node { int index_from; int index_to; }; 在一个容器里。在此条件下,两个节点相等 (a.index_from==b.index_from && a.index_to==b.index_to) ||(a.index_to==b.index_from && a.index_from==b.index_to) 节点需要按索引_从中排序 除了通过循环数组检查是否存
struct Node
{
int index_from;
int index_to;
};
在一个容器里。在此条件下,两个节点相等
(a.index_from==b.index_from && a.index_to==b.index_to)
||(a.index_to==b.index_from && a.index_from==b.index_to)
节点需要按索引_从中排序
除了通过循环数组检查是否存在外,还可以使用什么容器来执行此操作
操作:根据排序键从头到尾循环图形。添加唯一节点。使用std算法/函数对std容器的元素进行排序,您只需要运算符< 比较节点:
bool operator < (const Node& a, const Node& b) {
if(a.index_from < b.index_from) return true;
else if(a.index_from == b.index_from) {
if(a.index_to < b.index_to) return true;
}
return false;
}
但您似乎想要比较节点之间的链接:
bool operator < (const Node& a, const Node& b) {
int a0 = std::min(a.index_from, a.index_to);
int a1 = std::max(a.index_from, a.index_to);
int b0 = std::min(b.index_from, b.index_to);
int b1 = std::max(b.index_from, b.index_to);
if(a0 < b0) return true;
else if(a0 == b0) {
if(a1 < b1) return true;
}
return false;
}
注:
您可能有一个指向相反方向的等效链接
另一个的方向。
在比较链接时,您可能不使用
运算符,但传递给容器的比较对象
没有足够的代表发表评论,因此这是一个答案 奇怪的等式只是注意到两个节点之间的边是相同的,这是一个无向图,因此在讨论中的节点之间将有一条边,并且没有任何方向是固有的假设-即:给定任意两个节点a,b,如果a和b之间存在连接,那么edgea,b被认为等于边b.a 检查相等性会捕获向后的节点,因此这些节点不会进入有效的边描述集中,从而保留唯一性约束
因此,如果有节点a、b、c和d,并且在节点a和b、b和c、c和d以及a和d之间有连接,则a、b的边;公元前c、 将存储d和a,d,但存储b,a的边缘;c、 b;d、 c和d,a将被排除在外 您认为哪些容器可用于此操作?您希望使用此图执行哪些操作?@LightnessRacesinOrbit std::set?但是奇怪的平等又如何实现呢?