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

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

本文关键字:存储 std vector 检查 实例 是否      更新时间:2023-10-16

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

运行代码,我得到一个错误:

错误C2678: binary '==':没有找到带左操作数的操作符(或者没有可接受的转换)"

错误在哪里,我如何解决这个问题?

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

isElement

if(dataHandler[i] == element)

这是试图使用operator==比较两个A实例,但是你的A类没有实现任何这样的操作符过载。您可能想要实现一个类似的

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

同样,可以用std::find代替for循环重写isElement

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

编译器告诉你一切。为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;
    }
};

您必须为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();
}