【问题标题】:I want to check if a class instance is already stored in a std::vector我想检查一个类实例是否已经存储在 std::vector 中
【发布时间】:2015-08-09 15:20:03
【问题描述】:

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

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

错误 C2678: 二进制 '==': 未找到采用 tpye 'A' 左侧操作数的运算符(或没有可接受的转换)"

错误在哪里,我该如何解决?

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

【问题讨论】:

  • 您应该通过指针存储您的实例,或者实现operator==class A 的比较。
  • C++ object equality的可能重复
  • @cfh:“通过指针存储您的实例” - 这没有任何意义。如果你在存储指针,你就不是在存储实例。
  • @MikeSeymour:显然,我的意思是存储指向实例的指针。
  • @cfh:哪些实例?如果您将指针存储在向量中,您将它们存储在哪里?您的“简单”建议打开了一大堆蠕虫,将一个非常简单的数据结构变成了更难处理的东西。

标签: c++ vector operator-overloading


【解决方案1】:

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

【讨论】:

  • +1 可以,谢谢。我写了一个类似的运算符方法,只是没有两个 const 和 &,它不起作用,但为什么我必须这样做?
  • @RefMa77 如果参数类型只是A,那么您将把参数复制到operator==,这在这种情况下是不必要的。最后一个const 表示该函数没有modify any class members。但是 should work 除非您尝试在 constB 实例上调用 isElement。你能发布一个重现错误的例子吗?
  • 我犯了一个巨大的错误,只是比较实例,我必须比较每个变量。所以现在一切都很好:D
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    您必须为 A 类编写自己的 == 运算符,类似于

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

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

    【讨论】:

      【解决方案4】:

      您必须实现operator==

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

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

      【讨论】:

        猜你喜欢
        • 2014-03-30
        • 1970-01-01
        • 2015-03-10
        • 2019-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-17
        • 1970-01-01
        相关资源
        最近更新 更多