【问题标题】:iterate through list of linked list遍历链表列表
【发布时间】:2013-02-18 23:33:55
【问题描述】:

我是 C++ 的新手,对这个指针和东西感到头疼!

我需要遍历链表结构的列表,读取结构的数据并弹出该条目!

这是我的结构:

struct node {
    map<string,double> candidates;
    double pathCost;
    string source;
    node *next;             // the reference to the next node
};

通过阅读this 帖子,我创建了我的列表,如下所示:

list<node*> nodeKeeper;

然后初始化第一个值:

    node *head;
    head= new node;
    head->pathCost = 0.0;
    head->source="head";
    head->next = NULL; 

细填充列表和结构:

for(unsigned int i = 0; i < sourceSentence.size(); i++){

    node *newNode= new node;             //create a temporary node


    //DO STUFF HERE


    //push currunt node to stack
    nodeKeeper.push_back(newNode);

    head = newNode;

}

现在我有了结构列表,我想遍历它并弹出元素:

for (list<node*>::const_iterator it=nodeKeeper.begin();it!=nodeKeeper.end();it++){

    it->pop_front();

}

这给了我这个错误:

错误:在 '* 中请求成员 'pop_front' it.std::_List_const_iterator<_tp>::operator->()',它是 指针类型 'node* const' (也许你的意思是使用 '->' ?) make: *** [main3.o] 错误 1

看起来我的迭代器指向列表内部,而不是列表本身!

你能告诉我这里出了什么问题吗?!

【问题讨论】:

  • 如果允许使用 STL,为什么不使用 listlists?
  • @bilz 是的,我也试过了!我说我是 C++ 的新手,我只是在尝试所有阅读的内容
  • @AndyProwl 这有什么帮助?我需要指向下一个节点的指针!
  • @Moj list 是一个双向链表结构。每个元素都有一个指向下一个和前一个节点的指针。这就是你迭代它的方式。
  • @Moj:这就是list 为您所做的。我会从node 中删除next 成员,我会使用list&lt;list&lt;node&gt;&gt;(或者可能是vector&lt;list&lt;node&gt;&gt;,除非你有理由选择list

标签: c++ struct linked-list


【解决方案1】:

如果您的目标是拥有一个节点结构列表,则无需自己管理下一个指针。插入将保持不变(减去head = 行)

要弹出列表的所有元素,您可以执行类似

的操作
int sizeOfList = nodeKeeper.size();
for( int i =0; i < sizeOfList; i++) {
    //if you want to do something with the last element
    node * temp = nodeKeeper.back();
    //do stuff with that node

    //done with the node free the memory
    delete temp;
    nodeKeeper.pop_back();
}

在此处编译/运行示例:http://ideone.com/p6UlyN

【讨论】:

  • 谢谢@罗伯特。帮了大忙
【解决方案2】:

如果您只需要删除元素,请使用std::list::clear

nodeKeeper.clear();

要读取元素的内容,然后删除,试试这个:

for (std::list<node*>::const_iterator it = nodeKeeper.begin(); it != nodeKeeper.end(); ++it) {
    std::cout << (*it)->source;
    // do more reading

    nodeKeeper.pop_front();
}

或使用 C++11:

for (const auto& a : nodeKeeper) {
    std::cout << a->source;

    nodeKeeper.pop_front();
}

【讨论】:

  • @juanchopanza 不知道这种方法。我会在我的回答中使用它。谢谢
  • 如何访问每个元素的数据?类似于:nodeKeeper.front()->source;因为现在它只打印“head”的最后一个元素
  • @Moj 我正在更新我的答案。请稍等
  • @Moj BTW,应该是 (*it)-&gt;sourcenodeKeeper.pop_front()
  • @Moj 我的更新现在有帮助吗?我使用cout&lt;&lt; (*it)-&gt;source 读取数据,然后使用nodeKeeper.pop_front() 将其弹出。这对你有用吗?
猜你喜欢
  • 2017-09-03
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
相关资源
最近更新 更多