检查结构是否不在矢量中

Check if structure is not in vector

本文关键字:结构 是否 检查      更新时间:2023-10-16

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

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;

我的发现:

 if (find(closedList.begin(), closedList.end(), currentNode) == closedList.end() )
 {
 }
您需要

重载operator==

作为全局函数:

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的成员函数来做,推荐的方法是将operator==实现为一个自由函数(这样,两个参数都可以利用任何可能的隐式转换)。

关于浮点数比较的说明:由于浮点数的表示方式,比较它们并非易事。仅检查相等性可能不会产生预期的结果。例如,请参阅此问题以了解详细信息:浮点数和双重比较最有效的方法是什么?

您需要重载比较运算符。如果你对"=="的意图是"我的结构中包含的每个值是否等于这个其他结构中的相应成员",那么你可以这样写。

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