【问题标题】:C++ Iterate through a list of structs of structsC ++遍历结构的结构列表
【发布时间】:2018-10-14 10:53:58
【问题描述】:

我在访问结构中的结构列表时遇到问题:

struct  B{
  string word;
};

struct A{
  list<B> message;
};

将数据放入数据结构中是没有问题的:

list<A> messageList;
while(--there are messages to be found--){
  list<B> wordList;
  do{
    string buff;
    wordList.push_front({buff});
  }while(--there are words to be found--);
  messageList.push_front({wordList});
}

但知道我想阅读消息的每个单词:

list<A>::iterator itMessage;
for(itMessage = messageList.begin(); itMessage != messageList.end(); itMessage++){

我卡住了,我是不是用一个迭代器来制作一个迭代器?

  list<itMessage->message>::iterator itWord;

还是一个列表的列表?

  list<list<??>>::iterator itWord;

【问题讨论】:

  • 为什么不简单地使用两个基于范围的 for 循环和 auto 关键字?

标签: c++ list struct


【解决方案1】:

首先,迭代消息,然后迭代单词:

struct A {
    auto begin() {
        return message.begin();
    }
    auto end() {
        return message.end();
    }

    list<B> message;
};

for (auto& message : messageList)
    for (auto& word : message)
    {
        ...
    }

如果您想要对 messageList 中的单词进行单个迭代器,则必须自己编写。

【讨论】:

    猜你喜欢
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多