tags:

views:

168

answers:

4

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();  
}
+14  A: 

(*listMyClassIter)->PrintMeOut();

Novelocrat
+4  A: 
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();  
}
Kirill V. Lyadvinsky
+2  A: 

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);
Rick
"most compilers are picking up lambdas from C++0x" - "most" at this point are VC++10 (beta), Comeau (beta), and Intel. Specifically, g++ has no support for lambdas yet in any version. Much as I love lambdas, it's way too early to use them in responses to generic C++ questions.
Pavel Minaev
Thanks. I did include another response for precisely this reason, and perhaps 'some' or 'many' is a better term than 'most' I've been fortunate to have been working with them for a couple years now and I forget this at times, so it will be nice when g++ has them incorporated.
Rick
+5  A: 

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.

  1. Only calling end() once rather than each iteration.
  2. Remembering to use pre increment rather than post increment.
  3. Needing to work out the actual types of my iterators.
  4. I am sure there are more but its early in the morning here.
Martin York
yes this is quite good.
Rick
This is probably the better way to do it than my literal answer.
Novelocrat