简体   繁体   English

重载运算符<至(0,1)=(0,1)和(0,1)=(1,0)

[英]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 当我有一组simpleLink并插入(0,1)然后尝试插入(1,0)时,不应插入

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. 集合的大小应为1。

If you wish for two items in a set to compare equivalent, the comparitor must produce equivalence for (a,b) or (b,a). 如果您希望集合中的两个项目比较等效项,则比较器必须产生(a,b)或(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! 为此,您必须选择如何相对于所有orig和dest进行订购!

The following works by sorting orig and dest for each link, and then comparing the smallest. 下面的工作方式是为每个链接对orig和dest进行排序,然后比较最小的链接。 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)<(2 2)
  • (1 2) < (1 3) (1 2)<(1 3)

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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