在c ++ +链表中同时迭代多个链表 [英] Iterate through multiple linked lists at the same time in c++ +linked list

查看:125
本文介绍了在c ++ +链表中同时迭代多个链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行一项任务,该任务需要从包含多个char链接列表的链接列表计算一个指标(每个行都是一个链接列表,如图所示)。因此,我需要遍历每个包含第二行空间的节点,以检查四个其他空间(上,下,左,右)围绕多少空格。例如,参考下面的图表,第三行中的第二个空间由四个空格包围,因此count ++。 (H只是意味着非空格字符,对不起,我没有足够的声誉,张贴一个真实的图片)。



我允许使用STL链表库。我试图使用三个迭代器同时迭代三行。然而,代码变得很杂乱,甚至不能正常工作,因为每行有不同的长度。我一直在想这个解决方案两天,但因为我一直在练习C ++只有两个月,所以我可以想到的是相当有限。所以我想知道是否有人可以给我一个提示或更聪明的解决方案。



space |空间| --H - --H - - H - NULL | NULL



--- H - --H --- |空间|空间| --- H- | - H - NULL



--- H - 空间|空间|空间| - H空间| NULL



space | --H - 空间|空间| - H - NULL | NULL

解决方案

您可以使用 std :: vector c $ c> std :: list :: iterator s。如果迭代器不在相应的 list 上,你将有一个内循环, code>' end()。如果您的列表依次作为数组或向量提供,这将更容易。 p>

I am doing a task that requires to calculate a metric from a linked list that contains multiple linked lists of char (each row is a single linked list as shown in the graph). So I will need to iterate through every node that contains a space from the second row, to check how many spaces are surrounding by four other spaces (top, bottom, left, right). For instance, referring to the graph below, the second space in the third row is surrounding by four spaces, so count++. (the "H" just simply means non-space character, sorry that I don't have enough reputation to post a real picture).

I am allowed to used the STL linked list library. I was trying to use three iterators to iterate through three rows at the same time. However, the code gets really messy and does not even work correctly as each row has different lengths. I have been thinking the solution for two days, but as I've been practicing C++ for only two months, so what I could think of is pretty limited. So I am wondering if anyone could give me a hint or a smarter solution, please.

space | space | --H -- | --H -- | -- H -- | NULL| NULL

--- H --| --H ---| space | space | --- H- | -- H -- | NULL

--- H --| space | space | space | -- H-- | space| NULL

space | --H -- | space | space | -- H -- | NULL | NULL

解决方案

You can use a std::vector of std::list::iterators. You'd have an inner loop that just does whatever computation you want at each step, if the iterator isn't already at the corresponding list's end(). This will be a lot easier if your incoming lists are in turn provided as an array or a vector.

这篇关于在c ++ +链表中同时迭代多个链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆