我正在嘗試使用std::set
,我將在其中扔出一堆邊緣,並且只留下唯一的邊緣。我的邊緣在哪裏?
Edge
是兩個(整數索引)節點之間的一條線。邊緣(1,2)==(2,1)
,因爲這些邊緣是無向的。
雖然我遇到了一個令人費解的情況,在下面的代碼中標記爲//??
的部分,行爲不符合我的預期。
運行此代碼的結果僅保留2個邊(1,2)和(4,8)。 (2,1)被設置丟棄,但它不應該是,除非我激活operator==
中的註釋//|| (A==o.B && B==o.A)
部分!這裏發生了什麼?
這set<Edge>
執行讓我感覺..前衛。
#include <stdio.h>
#include <set>
using namespace std ;
struct Edge
{
int A,B ;
Edge(int iA, int iB) : A(iA), B(iB) {}
bool operator==(const Edge & o) const {
//??
return (A==o.A && B==o.B) ;//|| (A==o.B && B==o.A) ;
}
bool operator<(const Edge& o) const {//MUST BE CONST
return A < o.A && B < o.B ;
}
void print() const { printf("(%d, %d)", A,B) ; }
void compare(const Edge& o) const {
print() ;
if(*this==o) printf("==") ;
else printf("!=") ;
o.print() ;
puts("");
}
} ;
int main()
{
Edge e1(1, 2) ;
Edge e2(1, 2) ;
Edge e3(2, 1) ;
Edge e4(4, 8) ;
e1.compare(e2) ;
e1.compare(e3) ;
e1.compare(e4) ;
set<Edge> edges ;
edges.insert(e1) ;
edges.insert(e2) ;
edges.insert(e3) ;
edges.insert(e4) ;
printf("%d edges\n", edges.size()) ;
for(auto edge : edges)
{
edge.print();
}
}
@HunterMcMillen另外,'<'必須實現這一點(因爲它是內部集的順序相應的操作員)。 – Nobody
是的,它會在最後的實現中,我只是想知道爲什麼(2,1)被排除在set之外。已被註釋掉_ – bobobobo
嗯。那麼'(1,2)<(2,1)'是錯誤的,'(2,1)<(1,2)'也是錯誤的。 – bobobobo