且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-27 08:32:22

派对迟到了.但是:我会遍历索引.但不是使用经典的 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);