【问题标题】:C++ How to loop through a list of structs and access their propertiesC ++如何遍历结构列表并访问它们的属性
【发布时间】:2010-11-24 05:46:56
【问题描述】:

我知道我可以像这样遍历字符串列表:

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

但是我该怎么做呢?

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

或者如果有人可以用for_each 循环来解释如何做到这一点,那也会很有帮助,但从我读过的内容来看似乎更复杂。

非常感谢

【问题讨论】:

    标签: c++ list loops foreach struct


    【解决方案1】:

    就像Iterator-&gt;property 一样简单。您的第一次尝试几乎是正确的,由于运算符优先级,它只需要一些括号:(*Iterator).property

    为了使用 for_each,您必须将 cout 语句提升为函数或仿函数,如下所示:

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

    【讨论】:

      【解决方案2】:

      (*Iterator).property1Iterator-&gt;property1

      【讨论】:

        猜你喜欢
        • 2023-03-14
        • 2011-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-04
        • 2012-06-11
        • 1970-01-01
        • 2014-04-20
        相关资源
        最近更新 更多