Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector std::find() with vector of custom class

Tags:

c++

find

vector

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?

like image 571
user3453494 Avatar asked Dec 25 '22 10:12

user3453494


1 Answers

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.
}
like image 115
R Sahu Avatar answered Jan 08 '23 02:01

R Sahu