使用std :: set find和struct data

use*_*593 3 c++ equals std set comparator

typedef struct Edge
{
    int v1, v2, w;
    bool operator <(const Edge &rhs) const{
        bool b = v1 < rhs.v1 || v2 < rhs.v2;
        return (b);
    }
} edge;


template <class T>
struct my_less
{
    bool operator()(const T& _Left, const T& _Right) const
    {
        return (_Left < _Right);
    }
};

int main(int argc, char *argv[])
{
    set <edge, my_less<edge> > F;

    edge e3 = { 3, 3, 3};
    edge e4 = { 3, 7, 3};
    edge e5 = { 2, 7, 3};

    F.insert(e3);
    printf("e3 ? %d\n", F.find(e3)!=F.end()); // O
    printf("e4 ? %d\n", F.find(e4)!=F.end()); // O
    printf("e5 ? %d\n", F.find(e5)!=F.end()); // X

    //printf("%d\n", e3<e4);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)
If run this code, I got an error at "F.find(e5)!=F.end()" with following message.
"Debug Assertion Failed!. Expression: invalid operator < "

The condition of two edges of '(x,y), (p,q)' equality is 
 !(x < p || y < q) && !(p < x || q < y)

It can be '(x>=p && y>=q) && (p>=x && q>=y)'

I really don't know why assertion raised.
Is there something wrong?

Cor*_*lks 7

您的比较不会强制执行严格的排序.例如:

Edge e1;
Edge e2;

e1.v1 = 5;
e1.v2 = 4;

e2.v1 = 4;
e2.v2 = 5;

// e1 < e2 is true
// e2 < e1 is true
// So which one should we really trust? Neither, let's abort the program!
Run Code Online (Sandbox Code Playgroud)

你需要让你的<操作员真正地工作<.如果e1 < e2是真的,那么e2 < e1需要是假的.

这可能是你想要的,但要注意我还没有测试过:

return v1 < rhs.v1 || (v1 == rhs.v1 && v2 < rhs.v2);
Run Code Online (Sandbox Code Playgroud)

从理论上讲,这应该排序v1v2用来打破关系.

  • 编写正确的`operator <`的简单方法是遵循以下模式:`if(a!= rhs.a)返回<rhs.a; if(b!= rhs.b)返回b <rhs.b; /*等等*/; 返回false;` (2认同)