Reputation: 10234
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
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
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
Reputation: 40613
The C++ code is almost identical:
for (AbstractType* object: myList)
object->method();
Upvotes: 4
Reputation: 3147
Using C++ STL you have an iterator for this. After you defined it you use begin() and end() methods.
Upvotes: 0