【问题标题】:Is it possible in C++ to iterate over multiple iterators in a single loop sequentially?在 C++ 中是否可以在单个循环中按顺序迭代多个迭代器?
【发布时间】:2020-03-04 16:17:23
【问题描述】:

我知道,如果我使用实现 iterator 接口(提供 begin()end() 函数)的 c++ 容器,我可以使用这样的 for 循环对其进行迭代:

for (auto element : container) {
    process(element);
}

如果我有两个同类型容器的实例,我可以这样写代码

for (auto element : container1) {
    process(element);
}
for (auto element : container2) {
    process(element);
}

但是这会导致代码重复。我正在寻找一种方法来组合这两个容器,以便我可以一次迭代它们(即让 for 循环迭代第一个,然后继续迭代第二个)。像这样的:

for (auto element : container1 + container2) {
    process(element);
}

我知道我可以使用container1.insert(container1.end(), container2.begin(), container2.end()); 之类的东西来连接它们(如果它们恰好是向量),但我希望能够更一般地、就地、用一行而不修改任何一个容器来执行此操作。

【问题讨论】:

  • 核心 C++ 语言中没有类似的东西。
  • Boost 有几个实用工具可以派上用场stackoverflow.com/questions/14366576/…
  • 没有。基于范围的 for 的要点是它迭代指定的范围。嵌套循环有什么问题(例如,如果容器都保持不变,for (const auto &container: set_of_containers) for (const auto &element : container) process(element);)? (显然{} 如果事情更复杂,或者为了可读性,可以使用)。

标签: c++ for-loop iterator c++17


【解决方案1】:

不使用某种迭代器适配器,您可以只创建一个指向所有容器的指针/引用数组,然后循环它,运行一个内部循环来迭代当前容器的元素:

auto* containers[] = {&container1, &container2};
for (auto *container : containers) {
    for (auto &element : *container) {
        process(element);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 2022-01-11
    • 2016-05-06
    • 2013-08-01
    相关资源
    最近更新 更多