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);
这篇关于同时迭代两个或多个容器的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:同时迭代两个或多个容器的最佳方法是什么
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
