Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle and iterate through this list?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading