Search code examples
c++stdvector

Find if structures with same values exist in vector array


I want to check if there are structures with the same values in the vector array. May someone explain to me how should I do this?

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.}

As you can see I tried std::find function, and I think it should work ( this is the answer to most of these questions like mine). The only condition was to compare the same objects


Solution

  • What seems to be missing from your code is a definition of what it means for two of your mineCoordinate objects to be equal. If you add this

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

    then I think it will work too.

    You might have thought that this definition is so obvious that it doesn't need to be explicitly defined, but that is not correct.