STL find ()
Aug 5, 2010 at 1:00pm Aug 5, 2010 at 1:00pm UTC
Aloha everyone! I am trying to use the find () in the STL but I seem to be doing something wrong, but I can't figure out what. It looks as though I only need to implement the '==' operator, but it doesn't seem to call my class. Please help!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class myClass
{
public :
myClass(){}
~myClass(){}
friend bool operator ==(myClass& a, myClass& b);
};
bool operator ==(myClass& a, myClass& b) //this doesn't get called
{
cout << "in operator ==" << endl;
return true ;
}
int main()
{
myClass* a = new myClass();
myClass* b = new myClass();
vector<myClass*> list;
list.push_back(a);
list.push_back(b);
vector<myClass*>::iterator it = find(list.begin(), list.end(), a); //should call operator==
if ( it == list.end() )
cout<<"Not found" <<endl;
else
cout<<"Found" <<endl;
return 0;
}
after compiling and running, i get this output
1 2 3
g++ -Wall test_find.cpp -o test_find
./test_find
Found
as you can see, my '==' operator doesn't get called. any ideas why?
Aug 5, 2010 at 1:02pm Aug 5, 2010 at 1:02pm UTC
Yes, since you store pointers in your vector, operator== will be called on those - not on the instances of your class.
Aug 6, 2010 at 5:51pm Aug 6, 2010 at 5:51pm UTC
Athar, thanks! That indeed was my mistake. My solution was to wrap myClass and store that in the vector. That seems to have done the trick! Thanks again.
Aug 6, 2010 at 5:59pm Aug 6, 2010 at 5:59pm UTC
You don't want to name variables "list", there is already a std::list.
Topic archived. No new replies allowed.