Hi guys,
I have problem regarding find algorithm used in STL
Defination directly from book
The find algorithm is an operation (function) that can be applied to many STL containers. It searches a subrange of the elements in a container (or all the elements), looking for an element that is "equal to" a specified value; the equality operator (==) must be defined for the type of the container's elements.
In the defination above i'm having problem with the bold text
Now here is myClass as follows
- #include<iostream>
-
#include<vector>
-
#include<algorithm>
-
using namespace std;
-
-
class myClass
-
{
-
public:
-
myClass(){}
-
~myClass(){}
-
friend bool operator==(myClass& a, myClass& b);
-
};
-
typedef std::vector<myClass*> myClassList;
-
typedef std::vector<myClass*>::iterator myClassListIterator;
-
-
bool operator==(myClass& a, myClass& b) //this doesnt get called
-
{
-
return true;
-
}
-
-
int main()
-
{
-
myClass* a = new myClass();
-
myClass* b = new myClass();
-
-
myClassList list;
-
list.push_back(a);
-
list.push_back(b);
-
myClassListIterator it = find(list.begin(), list.end(), a); //should call operator==
-
if( it == list.end() )
-
cout<<"Not found"<<endl;
-
else
-
cout<<"Found"<<endl;
-
return 0;
-
}
But the problem is I'm unable to call the operator== defined in myClass. What is that I'm doing wrong in the above code????
Any comment will be highly appreciated
Here internally algorithm find is comparing two pointers
Since pointer of your class can't call the == operator
you have to pass the object
And you should use const myClass& as a parameter of == operator
because algorithm find is receiving your object using const & and
and there is no operator defined which will take your operands as const reference
So the final solution is like this
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class myClass
{
public:
myClass(){}
~myClass(){}
friend bool operator==(const myClass& a, const myClass& b); // Modified
};
typedef std::vector<myClass*> myClassList;
typedef std::vector<myClass>::iterator myClassListIterator; // Modified
bool operator==(const myClass& a, const myClass& b) //this doesnt get called // Modified
{
return true;
}
int main()
{
myClass* a = new myClass();
myClass* b = new myClass();
myClassList list;
list.push_back(a);
list.push_back(b);
myClassListIterator it = find(*list.begin(), *list.end(), *a); //should call operator== // Modified
if( it == *list.end() ) // Modified
cout<<"Not found"<<std::endl;
else
cout<<"Found"<<std::endl;
return 0;
}