c++ - 同时迭代两个或多个容器的最佳方法是什么

标签 c++ c++11 iterator containers

C++11 提供了多种迭代容器的方法。例如:

基于范围的循环

for(auto c : container) fun(c)

std::for_each

for_each(container.begin(),container.end(),fun)

但是,推荐的方法是迭代两个(或更多)相同大小的容器以完成以下操作:

for(unsigned i = 0; i < containerA.size(); ++i) {
  containerA[i] = containerB[i];
}

最佳答案

晚会有点晚了。但是:我会遍历索引。但不是使用经典的 for 循环,而是使用基于范围的 for 循环在索引上:

for(unsigned i : indices(containerA)) {
    containerA[i] = containerB[i];
}

indices 是一个简单的包装函数,它返回索引的(惰性求值)范围。由于实现(虽然简单)有点太长,无法在此处发布,you can find an implementation on GitHub .

此代码与使用手动的经典 for 循环一样高效

如果这种模式经常出现在您的数据中,请考虑使用另一种模式,该模式 zip 生成两个序列并生成一系列元组,对应于成对的元素:

for (auto& [a, b] : zip(containerA, containerB)) {
    a = b;
}

zip 的实现留给读者作为练习,但它很容易从 indices 的实现中得到。

(在 C++17 之前,您必须改为编写以下代码:)

for (auto&& items : zip(containerA, containerB))
    get<0>(items) = get<1>(items);

关于c++ - 同时迭代两个或多个容器的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12552277/

相关文章:

c++ - 为什么异常规范没有用?

c++ - 如何断言 std::mutex 是否被锁定?

c++ - 带有 enable_if : make default implementation 的部分模板函数特化

unit-testing - 在 C++ 中使用 gmock 模拟具体类

c++ - 对 mongo::curTimeMillis64() 的 undefined reference

c++ - STL 中的写时复制支持

c++ - 一个对象能知道它自己的常量吗?

c++ - 迭代器在 C++ 中的工作原理

c++ - C++ 中的 priority_queues

c++ - 实现 QAbstractItemModel 迭代器