why does the following not work?:
MyClass c{};
std::vector<MyClass> myVector;
std::find(myVector.begin(), myVector.end(), c);
This will give an error.
error: no match for 'operator==' (operand types are 'MyClass' and 'const MyClass')
However if I do the same thing with non-class datatypes instead of a "MyClass", everything works fine. So how to do that correctly with classes?
Documentation of std::find
from http://www.cplusplus.com/reference/algorithm/find/:
template <class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val);
Find value in range Returns an iterator to the first element in the range [first,last) that compares equal to val. If no such element is found, the function returns last.
The function uses
operator==
to compare the individual elements to val.
The compiler does not generate a default operator==
for classes. You will have to define it in order to be able to use std::find
with containers that contain instances of your class.
class A
{
int a;
};
class B
{
bool operator==(const& rhs) const { return this->b == rhs.b;}
int b;
};
void foo()
{
std::vector<A> aList;
A a;
std::find(aList.begin(), aList.end(), a); // NOT OK. A::operator== does not exist.
std::vector<B> bList;
B b;
std::find(bList.begin(), bList.end(), b); // OK. B::operator== exists.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With