C ++如何遍历结构列表并访问它们的属性 [英] C++ How to loop through a list of structs and access their properties
本文介绍了C ++如何遍历结构列表并访问它们的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
list< string> :: iterator Iterator;
for(Iterator = AllData.begin();
Iterator!= AllData.end();
Iterator ++)
{
cout<< \t+ * Iterator +\\\
;
}
但是我怎么能这样做?
list< CollectedData> :: iterator Iterator;
for(Iterator = AllData.begin();
Iterator!= AllData.end();
Iterator ++)
{
cout<< \t+ * Iterator.property1 +\\\
;
cout<< \t+ * Iterator.property2 +\\\
;
$ b 如果有人能解释如何用 for_each
循环,这也是非常有帮助的,但是从我读过的内容来看似乎更加复杂了。
非常感谢
解决方案 Iterator->属性您的第一次尝试几乎是正确的,由于运算符优先级,它只需要一些括号:(* Iterator).property
为了使用for_each,你必须把cout语句提升到一个函数或函子中,如下所示:
void printData AllDataType& data)
{
cout<< \ t+ data.property1 +\\\
;
cout<< \ t+ data.property2 +\\\
;
for_each(AllData.begin(),AllData.end(),printData);
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
解决方案 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);
这篇关于C ++如何遍历结构列表并访问它们的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文