Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate through a std::list<MyClass *> and get to the methods in that class from the iterator?

Tags:

c++

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();  
}     
like image 707
Loren C Fortner Avatar asked Sep 18 '09 17:09

Loren C Fortner


4 Answers

Use this method:

(*listMyClassIter)->PrintMeOut();
like image 140
Phil Miller Avatar answered Sep 28 '22 04:09

Phil Miller


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.
like image 37
Martin York Avatar answered Sep 28 '22 03:09

Martin York


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();  
}
like image 34
Kirill V. Lyadvinsky Avatar answered Sep 28 '22 05:09

Kirill V. Lyadvinsky


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);
like image 45
Rick Avatar answered Sep 28 '22 03:09

Rick