检查结构是否不在矢量中
Check if structure is not in vector
我有一个结构向量。我需要检查结构是否在向量中。整个结构,而不是任何特定成员。它在编译时向我抛出此错误:
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 */
}
相关文章:
- 具有引用成员的结构是否具有唯一的对象表示形式
- 用户定义的结构是否有默认C++比较器?
- 具有指向函数的指针的类内的结构是否需要类外函数的前向声明
- 助推.测试检查结构是否相等
- 使用字节数组具有单字节对齐方式的结构是否安全
- 在 for 循环中声明结构是否合法C++?
- 包含打包结构的结构是否自行打包?
- C++中的结构是否按顺序分配内存?每次都以某种方式获得指针比较的正确答案
- 使用运营商New分配的数据结构是否有任何副作用
- 标准库容器结构是否存储副本或引用?
- openMP 的 SIMD 结构是否需要特定类型的硬件?
- 检查 c++ 结构是否在集合中
- 在字节数组上转换具有虚函数的结构是否安全?
- std::unordered_map 如何释放使用 malloc 创建的结构.是否需要对地图进行 2 次查询
- Qt:通过深度复制访问列表中的数据结构是否应该比通过指针访问它慢得多
- 浮点结构是否有任何填充
- 在头文件中完成实现的结构是否需要 __attribute__((可见性( "default" )))?(C++)
- 检查结构是否不在矢量中
- C++:类/结构是否在编译时初始化过
- 对结构进行操作并将结果分配给同一结构是否是一种不好的做法?为什么