C ++ How to iterate over a list of structures and access their properties

I know that I can iterate over a list of strings as follows:

list<string>::iterator Iterator;
 for(Iterator = AllData.begin(); 
   Iterator != AllData.end();
   Iterator++)
 {
  cout << "\t" + *Iterator + "\n";
 }

but how can I do something like this?

list<CollectedData>::iterator Iterator;
 for(Iterator = AllData.begin(); 
   Iterator != AllData.end();
   Iterator++)
 {
  cout << "\t" + *Iterator.property1 + "\n";
  cout << "\t" + *Iterator.property2 + "\n";
 }

or if someone can explain how to do this with a loop for_each, this is also very useful, but it seemed more complicated from what I read.

Thank you very much

+3
source share
2 answers

It is as simple as that Iterator->property. Your first attempt is almost correct, it just needs parentheses due to operator precedence:(*Iterator).property

To use for_each, you need to remove the cout statuses in a function or functor, for example:

void printData(AllDataType &data)
{
    cout << "\t" + data.property1 + "\n";
    cout << "\t" + data.property2 + "\n";
}

for_each(AllData.begin(), AllData.end(), printData);
+9
source

(*Iterator).property1 or Iterator->property1

+3

Source: https://habr.com/ru/post/1716461/


All Articles