C++ 检查结构是否不在矢量中

C++ 检查结构是否不在矢量中,c++,struct,stdvector,C++,Struct,Stdvector,我有一个结构向量。我需要检查结构是否在向量中。整个结构,而不是任何特定的成员。它在编译时向我抛出以下错误: binary '==' : no operator found which takes a left-hand operand of type 'NavigationNode' (or there is no acceptable conversion) 我的结构: struct NavigationNode{ int x, y; //their x and y positi

我有一个结构向量。我需要检查结构是否在向量中。整个结构,而不是任何特定的成员。它在编译时向我抛出以下错误:

binary '==' : no operator found which takes a left-hand operand of type 'NavigationNode'
(or there is no acceptable conversion)
我的结构:

 struct NavigationNode{ 
    int x, y; //their x and y position on the grid
    float f, g, h;
    int parentGCost;
    int value;
};

NavigationNode currentNode;
向量

vector<NavigationNode> openList;
您需要重载运算符==

作为全球职能:

bool operator==( const NavigationNode& lhs, const NavigationNode& rhs )
{
    // compare lhs and rhs
}
或作为成员函数:

bool operator==( const NavigationNode& other ) const
{
    // compare this & other
}

您必须为自定义类型编写一个相等运算符。假设两个NavigationNode对象的所有变量都必须相同,则应如下所示:

bool floatEqual(float a, float b)
{
     // adapt this comparison to fit your use-case - see the notes below
     static const int EPSILON = 0.00001;    // arbitrarily chosen - needs to be adapted to the occuring values!
     return std::abs(a – b) <= EPSILON;
}

bool operator==(NavigationNode const & a, NavigationNode const & b)
{ 
    return a.x == b.x &&
        a.y == b.y &&
        floatEqual(a.f, b.f) &&
        floatEqual(a.g, b.g) &&
        floatEqual(a.h, b.h) &&
        a.parentGCost == b.parentGCost &&
        a.value == b.value;
}
即使您也可以将其作为NavigationNode的成员函数来实现,建议的方法是将运算符==作为自由函数来实现,这样,两个参数都可以利用任何可能的隐式转换

关于浮点比较的注意事项:由于浮点数是如何表示的,比较它们并不是一项简单的任务。仅仅检查是否相等可能不会得到期望的结果。有关详细信息,请参见此问题:
您需要重载比较运算符。 如果==的意图是my struct中包含的每个值都等于另一个struct中相应的成员,那么您可以编写它

bool operator==(const NavigationNode& lhs, const NavigationNode& rhs)
{
    return /* compare each member in here */
}

什么决定了两个NavigationNode对象之间的相等性?它们是否具有相同的结构值members@meWantToLearn-见DavidRodríguez dribeas在公认答案下的评论。a.x=b.x是一个赋值比较浮点是否相等可能很棘手,除非它是原始的副本,浮点数在数学上可能是等价的,这些运算在数学上最终会产生相同的值,但会与其他运算进行比较different@DavidRodríguez dribeas-很好的观点,我也在写同样的东西。@nyarlathotep-通常,fabs,与减法相结合并与ε相比较非常小的正浮点数,如.0001或其他;取决于必要的精度是一个很好的方法。
bool operator==(const NavigationNode& lhs, const NavigationNode& rhs)
{
    return /* compare each member in here */
}