我想检查 class 实例是否已存储在 std::vector 中

I want to check if a class instance is already stored in a std::vector

我希望标题能完整地描述我的问题。

运行 我得到错误的代码:

error C2678: binary '==':no operator found which takes a left-hand operand of tpye 'A' (or there is no acceptable conversion)"

哪里出错了,如何解决???

class A
{
  private: //Dummy Values
    int x;
    int y;
}

class B
{
  private:
    vector <A> dataHandler;

  public:
    bool isElement(A element);
    //Should return true if element exists in dataHandler
}

bool B::isElement(A element)
{
  int length = dataHandler.size();

  for(int i = 0; i<length; i++)
    {
      if(dataHandler[i] == element) //Check if element is in dataHandler
        return true;
    }
  return false;
}

编译器告诉你一切。为 class A 定义 operator==。将 class A 更新为如下内容:

class A
{
  private: //Dummy Values
    int x;
    int y;
  public:
    bool operator==(A const& rhs) const
    {
      return x == rhs.x && y == rhs.y;
    }
};

您必须为 class A 编写自己的 == 运算符,例如

bool operator==(const A &rhs) const
{
    return this->x == rhs.x && this->y == rhs.y;
}

否则无法知道如何比较 A 个对象。

您将必须实施 operator==

operator==的例子(内联非成员函数):

inline bool operator== (const A& left, const A& right){ 
    return left.getX() == right.getX() && left.getY() == right.getY();
}

isElement 内你有

if(dataHandler[i] == element)

这是尝试使用 operator== 比较两个 A 实例,但是您的 A class 没有实现任何此类运算符重载。你可能想实现一个类似于此的

class A
{
  private: //Dummy Values
    int x;
    int y;
  public:
    bool operator==(A const& other) const
    {
      return x == other.x && y == other.y;
    }
};

此外,isElement 可以使用 std::find 而不是 for 循环重写

bool B::isElement(A const& element) const
{
  return std::find(dataHandler.begin(), dataHandler.end(), element) != dataHandler.end();
}