Daniel Ribeiro
Daniel Ribeiro

Reputation: 10234

How to iterate std::list<AbstractType*>

I have this list:

std::list<AbstractType*> myList;

How can I iterate it, grab each object and perform some of their operations as normal instances?

In Java, it would be something like:

foreach(AbstractType object in myList)
    object.method();

Upvotes: 0

Views: 180

Answers (4)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

If not using C++ 11, you can make a free function acting on AbstractType and call it with std::for_each:

void doSomething(AbstractType& object) {
    object.doSomething();
}

int main() {
    // ...
    std::for_each(objects.begin(), objects.end(),
                  doSomething);
    // ...
}

Upvotes: 0

Andy Prowl
Andy Prowl

Reputation: 126412

If you are using C++11, see the answers by @Mankarse or @billz.

If you are using C++98, then you should do it like in the following example (or through an equivalent while loop:

#include <list>
#include <iostream>

int main()
{
    std::list<AbstractType*> l;
    // ...
    for (std::list<AbstractType*>::iterator i = l.begin(); i != l.end(); i++)
    {
        (*i)->DoSomething();
    }

    return 0;
}

EDIT

As @Mankarse pointed out in a comment, in C++98 you can also use BOOST_FOREACH:

BOOST_FOREACH(AbstractType* pObject, l)
{
    pObject->DoSomething();
}

Upvotes: 4

Mankarse
Mankarse

Reputation: 40613

The C++ code is almost identical:

for (AbstractType* object: myList)
    object->method();

Upvotes: 4

Mihai8
Mihai8

Reputation: 3147

Using C++ STL you have an iterator for this. After you defined it you use begin() and end() methods.

Upvotes: 0

Related Questions