English 中文(简体)
我如何通过一个 st子ate:<MyClass*>从编造者那里获得该类方法?
原标题:How do I iterate through a std::list<MyClass *> and get to the methods in that class from the iterator?
  • 时间:2009-09-18 17:01:19
  •  标签:

如果我有名单,

typedef std::list<MyClass *> listMyClass;

我如何通过这些方法加以利用和掌握这一类方法?

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();  
}     
最佳回答

使用这种方法:

(*listMyClassIter)->PrintMeOut();
问题回答

供职:

    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.
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();  
}

st:对于_子来说,令人难以置信,因此,一些编汇者现在从C++0x中挑选了拉姆布达斯,使这更具有启发性。

typedef std::list<MyClass*> MyClassList;
MyClassList l;
for_each(l.begin(),l.end(),[](MyClass* cur)
{
   cur->PrintMeOut();
});

for(和 algorithm的其余部分)有助于掩盖变异者与类型之间的抽象。 还指出,现在我拥有这种微薄的“lam”功能(或它也可以成为一种ctor子),这种功能更可检测、更可模拟、更可复制等。

如果我回到而不是,使用拉姆布达斯,我可以沿着这样做的方法形成一种立场。

void PrintMyClass(MyClass* cur)
{
    cur->PrintMeOut();
}

而现在则看着:

typedef std::list<MyClass*> MyClassList;
MyClassList l;
for_each(l.begin(),l.end(),&PrintMyClass);




相关问题
热门标签