How can I iterate over two vectors simultaneously using BOOST_FOREACH?(如何使用 BOOST_FOREACH 同时迭代两个向量?)
问题描述
我想用 BOOST FOREACH 复制以下内容
I'd like to replicate the following with BOOST FOREACH
std::vector<int>::const_iterator i1;
std::vector<int>::const_iterator i2;
for( i1 = v1.begin(), i2 = v2.begin();
i1 < v1.end() && i2 < v2.end();
++i1, ++i2 )
{
doSomething( *i1, *i2 );
}
推荐答案
同时迭代两件事称为zip"(来自函数式编程),Boost 有一个 zip 迭代器:
Iterating over two things simultaneously is called a "zip" (from functional programming), and Boost has a zip iterator:
zip 迭代器提供并行迭代多个同时控制序列.构建了一个 zip 迭代器来自迭代器元组.移动 zip 迭代器会移动所有并行迭代器.取消引用 zip 迭代器会返回一个元组包含取消引用各个迭代器的结果.
The zip iterator provides the ability to parallel-iterate over several controlled sequences simultaneously. A zip iterator is constructed from a tuple of iterators. Moving the zip iterator moves all the iterators in parallel. Dereferencing the zip iterator returns a tuple that contains the results of dereferencing the individual iterators.
请注意,它是一个迭代器,而不是一个范围,因此要使用 BOOST_FOREACH
,您必须将其中的两个放入一个 iterator_range 或 pair
.所以它不会很漂亮,但稍加注意,你可能会想出一个简单的 zip_range
并编写:
Note that it's an iterator, not a range, so to use BOOST_FOREACH
you're going to have to stuff two of them into an iterator_range or pair
. So it won't be pretty, but with a bit of care you can probably come up with a simple zip_range
and write:
BOOST_FOREACH(boost::tuple<int,int> &p, zip_range(v1, v2)) {
doSomething(p.get<0>(), p.get<1>());
}
或者 2 的特殊情况并使用 std::pair
而不是 boost::tuple
.
Or special-case for 2 and use std::pair
rather than boost::tuple
.
我想既然 doSomething
可能有参数 (int&, int&)
,实际上我们想要一个 tuple
I suppose that since doSomething
might have parameters (int&, int&)
, actually we want a tuple<int&,int&>
. Hope it works.
这篇关于如何使用 BOOST_FOREACH 同时迭代两个向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 BOOST_FOREACH 同时迭代两个向量?


- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16