Pair equal operator overloading for inserting into set

Posted by Petwoip on Stack Overflow See other posts from Stack Overflow or by Petwoip
Published on 2012-03-24T05:06:21Z Indexed on 2012/03/24 5:29 UTC
Read the original article Hit count: 154

Filed under:
|
|
|

I am trying to add a pair<int,int> to a set. If a pair shares the same two values as another in the set, it should not be inserted.

Here's my non-working code:

typedef  std::pair<int, int> PairInt;

template<>
bool std::operator==(const PairInt& l, const PairInt& r) 
{
    return (l.first == r.first && l.second == r.second) ||
           (l.first == r.second && l.second == r.first);
}

int main()
{
    std::set<PairInt> intSet;
    intSet.insert(PairInt(1,3));
    intSet.insert(PairInt(1,4));
    intSet.insert(PairInt(1,4));
    intSet.insert(PairInt(4,1));
}

At the moment, the (4,1) pair gets added even though there is already a (1,4) pair. The final contents of the set are:

(1 3)
(1 4)
(4 1)

and I want it to be

(1 3)
(1 4)

I've tried putting breakpoints in the overloaded method, but they never get reached. What have I done wrong?

© Stack Overflow or respective owner

Related posts about c++

Related posts about operator-overloading