I have a vector which contains class objects of classObjects

vector<classObjects> classObjectVector;

I am trying to use std::find to search for a record in my vector, but I get an error
message

error

Invalid operands to binary expression 

due to this line.

if (std::find(classObjectVector.begin(), classObjectVector.end(), "aElement") != classObjectVector.end())   
{
            //found
}

do I have to do something addtional to make it work?
I might have guess that I might need to do perhaps a operator overloading
something like this

   friend bool operator () (classObjects &objectOne) {
    return (objectOne);
   };

and after that I will intialize it like this

  if (std::find(classObjectVector.begin(), classObjectVector.end(), classObjects("aElement")) != classObjectVector.end())   
{
            //found
}

I am not really sure how should I use std::find with a vector containing class objects. I just made some assumptions.Need help and advice. thanks

Recommended Answers

All 5 Replies

The default find uses relational operators overloaded by the contained type (operator== to be precise). If you don't have those, you can either add them or use find_if with a predicate that handles a custom comparison.

I see. Thanks for your kind advice and suggestion but may I know why does the error
shows

 Invalid operands to binary expression 

on this line?

  if (std::find(classObjectVector.begin(), classObjectVector.end(), classObjects("aElement")) != classObjectVector.end())   
{
        //found
}

Because somewhere in the implementation of the std::find function, there is a comparison of two classObjects objects, i.e., there is a line like (o1 == o2) where o1,o2 are objects of class classObjects. The error tells you that the operands to the == operator (binary expression) are invalid, i.e., there is no valid == operator for the class classObjects. You need to define an operator overload for that class, something like this:

bool operator==(const classObjects& lhs, const classObjects& rhs) {
  // some code that returns true if lhs and rhs are equal.
};

Or it could be a friend function too, if you need access to private members of the class. It could also be a member function, but that's not recommended in this case.

Thanks for your kind advice and suggestion but may I know why does the error shows

For the same reason you can't say classObjects("foo") == classObjects("bar"). User defined types must explicitly support this syntax through overloaded operators, and find uses that syntax internally.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.