查找向量数组中是否存在相同值的结构



我想检查向量数组中是否有具有相同值的结构。有人能告诉我该怎么做吗?

struct mineCoordinate{
int x;
int y;
};
std::vector<mineCoordinate> mines;  // vector array
if(std::find(mines.begin(), mines.end(), mineCoordinate{userInputX,userInputY}) != mines.end()) { 
//do something if true.}

正如你所看到的,我尝试了std::find函数,我认为它应该工作(这是大多数问题(像我的问题)的答案。唯一的条件是比较相同的对象

您的代码中似乎缺少的是两个mineCoordinate对象相等的定义。如果你加上

bool operator==(const mineCoordinate& a, const mineCoordinate& b)
{
return a.x == b.x && a.y == b.y;
}

那么我想它也会成功的。

你可能认为这个定义很明显,不需要显式定义,但这是不正确的。

如果您使用的是c++ 20,您可以默认使用==操作符吗:

struct mineCoordinate 
{
int x;
int y;
bool operator==(const mineCoordinate&) const = default;
};

最新更新