同时迭代两个或多个容器的最佳方法是什么 [英] What's the best way to iterate over two or more containers simultaneously

查看:19
本文介绍了同时迭代两个或多个容器的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);

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

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