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

I hope the title fully describes my problem.

After running the code, I get the error:

error C2678: binary '==': no ​​operator found that accepts the left tpye operand 'A' (or no acceptable conversion) "

Where is the error and how can I fix the problem ???

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

      

+3


source to share


4 answers


Inside isElement

you have

if(dataHandler[i] == element)

      

This is an attempt to compare two instances A

using operator==

, but your class A

does not implement such operator overloading. You probably want to implement similar to this



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

      

Alternatively, isElement

you can rewrite using std::find

instead of a loopfor

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

      

+4


source


The compiler tells you everything. Specify operator==

for class A

. Update class A

something like this:



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

      

+2


source


you need to write your own operator ==

for the class A

, something like

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

      

otherwise there is no way to know how to compare objects A

.

0


source


You will need to follow through operator==

.

Example operator==

(built-in function is not member):

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

      

0


source







All Articles