我想用 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_range或 pair
.所以它不会很漂亮,但稍加注意你可能会想出一个简单的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/