c++ - 我想检查一个类实例是否已经存储在 std::vector 中

标签 c++ vector operator-overloading

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

运行代码出现错误:

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

最佳答案

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

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

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

关于c++ - 我想检查一个类实例是否已经存储在 std::vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30484156/

相关文章:

c++ - 将异步操作的处理程序绑定(bind)到另一个类的非静态成员

c++ - vector vector 的智能指针或常规指针

Matlab:索引向量值与固定值相同

c++ - C++ 错误 : redefinition of class constructor using templates

c# - 使用 Google Protocol Buffer 和 Protobuf-C# 将双重属性从 C++ 传输到 C# 时出现问题

Python 对于 __iter__ 的定义实现抛出 TypeError

c++ - 没有找到 << 运算符,尽管定义了一个运算符,但它接受类型为 Foo 的右手操作数

c++ - 实现模板运算符非友元

c++ - C++ 中的嵌套隐式转换

c++ - 矩阵和 vector 乘法,输出不正确的乘积