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