且构网

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

如何使用 BOOST_FOREACH 同时迭代两个向量?

更新时间:2023-11-22 23:33:22

同时迭代两件事称为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_rangepair.所以它不会很漂亮,但稍加注意,你可能会想出一个简单的 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.