RefMa77
RefMa77

Reputation: 293

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

I hope the title describes my problem completely.

Running the code I get an error:

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

Where is the mistake 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;
}

Upvotes: 3

Views: 238

Answers (4)

banach-space
banach-space

Reputation: 1811

Compiler tells you everything. Define operator== for class A. Update class A to 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;
    }
};

Upvotes: 2

Praetorian
Praetorian

Reputation: 109119

Within isElement you have

if(dataHandler[i] == element)

This is attempting to compare two A instances using operator==, but your A class doesn't implement any such operator overload. You probably want to implement one 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;
    }
};

Also, isElement can be rewritten using std::find instead of a for loop

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

Upvotes: 4

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 8066

You will have to implement the operator==.

Example of operator== (inline non-member function):

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

Upvotes: 0

dlavila
dlavila

Reputation: 1212

you have to write your own == operator for class A, something like

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

otherwise there's no way to know how to compare A objects.

Upvotes: 0

Related Questions