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

What#39;s the best way to iterate over two or more containers simultaneously(同时迭代两个或多个容器的最佳方法是什么)
本文介绍了同时迭代两个或多个容器的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

C++11 provides multiple ways to iterate over containers. For example:

for(auto c : container) fun(c)

std::for_each

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

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

However what is the recommended way to iterate over two (or more) containers of the same size to accomplish something like:

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

推荐答案

派对迟到了.但是:我会遍历索引.但不是使用经典的 for 循环,而是使用基于范围的 for 循环在索引上:

Rather late to the party. But: I would iterate over indices. But not with the classical for loop but instead with a range-based for loop over the indices:

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

indices 是一个简单的包装函数,它返回索引的(惰性求值)范围.由于实现(虽然简单)有点太长,无法在此处发布,您可以在 GitHub 上找到实现.

indices is a simple wrapper function which returns a (lazily evaluated) range for the indices. Since the implementation – though simple – is a bit too long to post it here, you can find an implementation on GitHub.

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

This code is as efficient as using a manual, classical for loop.

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

If this pattern occurs often in your data, consider using another pattern which zips two sequences and produces a range of tuples, corresponding to the paired elements:

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

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

The implementation of zip is left as an exercise for the reader, but it follows easily from the implementation of indices.

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

(Before C++17 you’d have to write the following instead:)

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

这篇关于同时迭代两个或多个容器的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)