如何遍历std :: list <myclass * =“”>并从迭代器中获取该类中的方法?</myclass>

时间:2009-09-18 17:01:20

标签: c++

如果我有列表,

typedef std::list<MyClass *> listMyClass;

如何迭代它们并获取该类中的方法?

这是我尝试过的,但事实并非如此: (MyClass :: PrintMeOut()是一种公共方法)

for(
    listMyClass::iterator listMyClassIter = listMyClass.begin();
    listMyClassIter != listMyClass.end();
    listMyClassIter ++)
{
    listMyClassIter->PrintMeOut();  
}     

4 个答案:

答案 0 :(得分:21)

使用此方法:

(*listMyClassIter)->PrintMeOut();

答案 1 :(得分:11)

for_each和函数指针:

    std::for_each(  listMyClass.begin(),
                    listMyClass.end(),
                    std::mem_fun(&MyClass::PrintMeOut)
                 );

我更喜欢使用for_each()构造而不是编写自己的循环 它使它看起来整洁,并做了所有我需要额外代码的东西。

  1. 只调用end()一次而不是每次迭代。
  2. 记住使用预增量而不是增量。
  3. 需要计算我的迭代器的实际类型。
  4. 我相信在这里早上还有更多。

答案 2 :(得分:4)

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

答案 3 :(得分:2)

std :: for_each in非常适合这种情况,一些编译器现在从C ++ 0x中获取lambdas,这使得这更加直观。

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

for_each(以及其余算法)有助于掩盖迭代器和类型之间的抽象。还要注意,现在我有了这个小小的lambda函数(或者它也可能是一个函子),它更易于测试,可模拟,可替换等。

如果我使用lambdas返回 not ,我可以构建一个方法来执行此操作,这是可测试的:

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

,for_each代码现在看起来像这样:

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