2013-10-24 47 views
0

我知道你可以通過這樣的容器重複的對(或更多):迭代通過C++對象

for(double x : mycontainer) 

這類似於Python的

不過,有時我需要訪問到另一個具有相同索引的容器中的元素,我不得不做一個普通的for循環。在Python中,或者,我可以(對於兩個或多個列表):

for (x,y) in zip(xlist, ylist): 

C++中是否有類似的東西?

+0

升壓[郵編迭代](http://www.boost.org/doc/庫/發行/庫/迭代器/ DOC/zip_iterator.html)。 –

+0

@JerryCoffin不錯。但我認爲在C++ 11標準中會有一些東西? – sashkello

+0

儘管一些可變參數模板的示例代碼(在§14.5.3/ 5中)看起來很可疑,但我認爲標準並不包含zip迭代器(儘管如此)。 –

回答

0

我知道的最接近的模擬是Boost的zip iterator

在典型情況下,你會使用boost::make_zip_iteratorboost:make_tuple一起,所以你最終的東西,如:

boost::make_zip_iterator(boost:make_tuple(xlist.begin(), ylist.begin())) 

和:

boost::make_zip_iterator(boost::make_tuple(xlist.end(), ylist.end())) 

這是不幸的是,相當有點比Python版本冗長,但有時候這就是生活。

2

最近的東西,我知道的是boost::combine(雖然,我沒有看到它的文檔 - 實際上,有trac ticket添加它)。它使用boost::zip_iterator內部,但它更方便:

LIVE DEMO

#include <boost/range/combine.hpp> 
#include <iostream> 

int main() 
{ 
    using namespace boost; 
    using namespace std; 

    int x[3] = {1,2,3}; 
    double y[3] = {1.1, 2.2, 3.3}; 

    for(const auto &p : combine(x,y)) 
     cout << get<0>(p) << " " << get<1>(p) << endl; 
} 

輸出是:

1 1.1 
2 2.2 
3 3.3