C++ How to loop through a list of structs and acce

2020-03-24 05:50发布

I know I can loop through a list of strings like this:

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 for_each loop, that would be very helpful as well, but it seemed more complicated from what I've read.

thank you so much

2条回答
可以哭但决不认输i
2楼-- · 2020-03-24 06:28

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

In order to use for_each, you would have to lift the cout statments into a function or functor like so:

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

for_each(AllData.begin(), AllData.end(), printData);
查看更多
ゆ 、 Hurt°
3楼-- · 2020-03-24 06:44

(*Iterator).property1 or Iterator->property1

查看更多
登录 后发表回答