gpt4 book ai didi

c++ - 使用 std::set 查找结构数据

转载 作者:太空狗 更新时间:2023-10-29 20:15:18 27 4
gpt4 key购买 nike

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;
}
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?

最佳答案

您的比较并未强制执行严格的排序。例如:

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!

您需要制作您的 <运算符实际上像 < 一样工作应该。如果e1 < e2为真,则e2 < e1必须是假的。

认为这可能是您想要的,但请注意我还没有测试过:

return v1 < rhs.v1 || (v1 == rhs.v1 && v2 < rhs.v2);

理论上,这应该v1排序,并使用 v2打破联系。

关于c++ - 使用 std::set 查找结构数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13548472/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com