简体   繁体   中英

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

why does the following not work?:

MyClass *c = new MyClass();
std::vector<MyClass> myVector;
std::find(myVector.begin(), myVector.end(), *c)

This will bring an error. I cannot remember the exact error, sorry for that, but it said something like MyClass and const MyClass cannot be compared by the Operator==

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.
}

You can't compare two objects of your own class type unless you have overloaded the operator== to provide such a function. std::find() uses your overloaded operator== to compare objects in the range of iterators you offered acquiescently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM