Home > Back-end >  How to handle and iterate through this list?
How to handle and iterate through this list?

Time:02-15

I have this type of list:

std::list<MyClass*>*

I want to iterate through this list and I also want to call the methods of MyClass, I want to do something like this:

std::list<MyClass*>* elements;

for (?)
{
    std:: cout << elements[i]->Membermethod(); << std::endl;
}

How can I do it?

CodePudding user response:

std::list<MyClass*>* elements;
for (auto it = elements->begin(); it != elements->end();   it)
{
    std::cout << (*it)->Membermethod() << std::endl;
}

note that its highly recommend not to put raw pointers in collections, use std::shared_ptr or std::unique_ptr

Much cleaner (also in c 11) is a 'ranged for'

for (auto pel : *elements) {
    std::cout << (*pel)->Membermethod() << std::endl;

}
  • Related