我怎么可以遍历两个向量同时使用BOOST_FOREACH? [英] How can I iterate over two vectors simultaneously using BOOST_FOREACH?

查看:95
本文介绍了我怎么可以遍历两个向量同时使用BOOST_FOREACH?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想复制与BOOST FOREACH以下

 的std ::矢量<&INT GT; ::为const_iterator I1;
的std ::矢量<&INT GT; ::为const_iterator I2;
为(I1 = v1.begin(),I2 = v2.begin();
     I1< v1.end()及&放大器; I2< v2.end();
     ++ I1,I2 ++)
{
     DoSomething的(* I1,I2 *);
}


解决方案

遍历两件事情同时被称为拉链(从函数式编程),和的升压有一个拉链的迭代器


  

拉​​链迭代器提供了并行迭代数的能力
  同时控制序列。的zip迭代器构造
  从迭代器的元组。移动压缩迭代器将所有的
  迭代器并联。解引用压缩迭代器返回一个元组
  包含非关联个人迭代器的结果。


请注意,这是一个迭代器,而不是一个范围,所以使用 BOOST_FOREACH 你将不得不东西他们两个到<一个href=\"http://www.boost.org/doc/libs/1_47_0/libs/range/doc/html/range/reference/utilities/iterator_range.html\">iterator_range或。所以它不会是pretty,但有一点照顾你也许可以想出一个简单的 zip_range 写:

  BOOST_FOREACH(升压::元组LT; INT,INT&GT;&安培; P,zip_range(V1,V2)){
    doSomething的(p.get&℃,GT(),p.get&所述1为卤素;());
}

或其他特殊情况2,并使用的std ::对,而不是的boost ::元组

我想,既然 DoSomething的可能有参数(INT和放大器;,INT和放大器;),其实我们希望有一个元组LT; INT和放大器;,&INT放大器;&GT; 。希望它的工作原理。

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 );
}

解决方案

Iterating over two things simultaneously is called a "zip" (from functional programming), and 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.

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>());
}

Or special-case for 2 and use std::pair rather than boost::tuple.

I suppose that since doSomething might have parameters (int&, int&), actually we want a tuple<int&,int&>. Hope it works.

这篇关于我怎么可以遍历两个向量同时使用BOOST_FOREACH?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆