If I have the list,
typedef std::list<MyClass *> listMyClass;
How do I iterate through them and get to the methods in that class?
This is what I’ve tried, but that is not it: (MyClass::PrintMeOut() is a public method)
for(
listMyClass::iterator listMyClassIter = listMyClass.begin();
listMyClassIter != listMyClass.end();
listMyClassIter ++)
{
listMyClassIter->PrintMeOut();
}
Use this method:
(*listMyClassIter)->PrintMeOut();
for_each and function pointer:
std::for_each( listMyClass.begin(),
listMyClass.end(),
std::mem_fun(&MyClass::PrintMeOut)
);
I prefer using the for_each() construct rather than writting my own loop.
It makes it look neat and does all the things I would otherwise need extra code for.
typedef std::list<MyClass*> listMyClass;
listMyClass instance; // instance, you shouldn't use type in the following loop
for( listMyClass::iterator listMyClassIter = instance.begin(); // not listMyClass.begin()
listMyClassIter != instance.end(); // not listMyClass.end()
listMyClassIter ++)
{
(*listMyClassIter)->PrintMeOut();
}
std::for_each in is incredibly well suited for this, some compilers are now picking up lambdas from C++0x which makes this even more intuitive.
typedef std::list<MyClass*> MyClassList;
MyClassList l;
for_each(l.begin(),l.end(),[](MyClass* cur)
{
cur->PrintMeOut();
});
for_each (and the rest of the algorithms) help mask the abstraction between the iterators and types. Also note that now I have this little tiny lambda function (or it could be a functor too) which is more testable, mockable, replacable etc.
If I go back to not using lambdas I can build a stand along method to do this, which is testable:
void PrintMyClass(MyClass* cur)
{
cur->PrintMeOut();
}
and the for_each code now looks like this:
typedef std::list<MyClass*> MyClassList;
MyClassList l;
for_each(l.begin(),l.end(),&PrintMyClass);
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