【问题标题】:Iterate through multiple linked lists at the same time in c++ +linked listc++++链表中同时遍历多个链表
【发布时间】:2014-05-03 13:57:06
【问题描述】:

我正在执行一项任务,该任务需要从包含多个 char 链表的链表中计算指标(如图所示,每一行都是一个链表)。所以我需要遍历每个包含第二行空格的节点,以检查有多少空格被其他四个空格(顶部、底部、左侧、右侧)包围。例如,参考下图,第三行的第二个空格被四个空格包围,所以 count++。 (“H”只是简单的表示非空格字符,对不起,我没有足够的声誉来发布真实的图片)。

我被允许使用 STL 链表库。我试图使用三个迭代器同时遍历三行。但是,代码变得非常混乱,甚至无法正常工作,因为每一行都有不同的长度。我已经考虑了两天的解决方案,但是由于我练习 C++ 才两个月,所以我能想到的非常有限。所以我想知道是否有人可以给我一个提示或更聪明的解决方案。

空格 |空间 | --H -- | --H -- | -- H -- |空|空

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

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

空格 | --H -- |空间 |空间 | -- H -- |空 |空

【问题讨论】:

  • 您可以保留迭代器的 std::list、std::array 或 std::vector。
  • 为了清楚起见,您使用的是std::list<std::list<char>>;那是对的吗?与尝试发布描述段落相比,代码会更清楚地说明您实际在做什么。不要试图告诉我们关于代码,除非你也打算发布它。只有这样,我们才有可能看到不正当路径的明显伪影。

标签: c++ list


【解决方案1】:

以下可能会有所帮助:(在 C++11 中):Live example

std::size_t countSpaceSurroundBySpace(const std::list<std::list<char>>& l)
{
    if (l.size() < 3u) {
        return 0u;
    }
    auto it1 = l.begin();
    auto it2 = std::next(it1);
    auto it3 = std::next(it2);
    std::size_t count = 0u;

    for (; it3 != l.end(); ++it1, ++it2, ++it3) {
        // pointers on the 5 characters
        std::list<char>::const_iterator its[5] = {
            it1->begin(),
            it2->begin(),
            it2->begin(),
            it2->begin(),
            it3->begin()
        };
        if (its[0] == it1->end()) { continue; }
        ++its[0];
        if (its[2] == it2->end()) { continue; }
        ++its[2];
        ++its[3];
        if (its[3] == it2->end()) { continue; }
        ++its[3];
        if (its[4] == it3->end()) { continue; }
        ++its[4];
        for (; its[0] != it1->end() && its[3] != it2->end() && its[4] != it3->end();) {
            if (std::all_of(std::begin(its), std::end(its), [](std::list<char>::const_iterator it) { return *it == ' '; })) {
                ++count;
            }
            for (auto& it : its) {
                ++it;
            }
        }
    }
    return count;
}

【讨论】:

    【解决方案2】:

    您可以使用std::vectorstd::list::iterators。如果iterator 尚未位于相应的listend() 中,那么您将拥有一个内部循环,它只在每一步执行您想要的任何计算。如果您传入的lists 反过来作为数组或vector 提供,这将容易得多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 2018-11-23
      • 2017-09-03
      • 2012-09-17
      相关资源
      最近更新 更多