c++ - 如何使用 BOOST_FOREACH 同时迭代两个 vector ?

标签 c++ boost iterator boost-foreach

我想用 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 has a zip iterator :

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并写:

BOOST_FOREACH(boost::tuple<int,int> &p, zip_range(v1, v2)) {
    doSomething(p.get<0>(), p.get<1>());
}

或 2 的特殊情况并使用 std::pair而不是 boost::tuple .

我想自从 doSomething可能有参数(int&, int&) ,实际上我们想要一个 tuple<int&,int&> .希望它有效。

关于c++ - 如何使用 BOOST_FOREACH 同时迭代两个 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7286755/

相关文章:

java - 在 Java 中使用 finalize() 是否合适?

c++ - 如果 I/O read() 处于阻塞阶段,如何使用 Ctrl+C 退出 C++ 程序?

c++ - 为什么我的 C++ Boost ASIO HTTP 客户端返回不完整的响应?

python 3 : Checking next value of an iterator without iterating

java - 对于使用 Java Iterator 的每个循环

c++ - C 和 C++ 中的多字 rune 字

C++ LoadLibrary 不工作

c++ - const boost::shared_ptr<T>& 作为函数参数的目的?

c++ - 使用 BOOST_FOREACH 遍历目录中的所有文件

c++ - 为什么我不能取消引用迭代器?