简体   繁体   中英

Overloading operator< to (0, 1) = (0, 1) and (0, 1) = (1, 0)

How can i change the operator< to make my logic work?

Im trying like this, but it is not working.

struct simpleLink {
    int orig;
    int dest;

    bool operator<(const simpleLink& otherLink) const
    {
        if(orig == otherLink.orig)
            return dest < otherLink.dest;
        else if (orig == otherLink.dest)
            return dest < otherLink.orig;
        else
            return orig < otherLink.orig;
    }

}

From my point of view it should be working, but it isn't...

When i have a set of simpleLink and i insert (0, 1) and then i try to insert (1, 0) , it should not insert

Example:

int main() {

    set<simpleLink> test;

    simpleLink secureLink;
    secureLink.orig = 0;
    secureLink.dest = 1;

    simpleLink secureLink2;
    secureLink2.orig = 1;
    secureLink2.dest = 0;

    cout << secureLink.orig << " " << secureLink.dest << endl;
    cout << secureLink2.orig << " " << secureLink2.dest << endl;

    test.insert(secureLink);
    test.insert(secureLink2);

    cout << "Test Size:" << test.size() << endl;

    return 0;
}

Output is:

0 1
1 0
Test Size: 2

The set's size should be 1.

If you wish for two items in a set to compare equivalent, the comparitor must produce equivalence for (a,b) or (b,a). Your function does not do that.

It would appear that you would like to ignore any two that compare equal and sort based upon the unequals?

For this you must choose how to order all orig and dest relative to each other!

The following works by sorting orig and dest for each link, and then comparing the smallest. Only if the smallest are equal do we compare the larger.

bool operator<(const simpleLink& that) const
{
  auto this2 = std::minmax( orig,      dest );
  auto that2 = std::minmax( that.orig, that.dest );

  return (this2.first != that2.first) 
       ? (this2.first  < that2.first)
       : (this2.second < that2.second);
}

Examples:

  • (1 2) < (2 2)
  • (1 2) < (1 3)

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM