Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining iterators for C++

Tags:

c++

iterator

Python's itertools implement a chain iterator which essentially concatenates a number of different iterators to provide everything from single iterator.

Is there something similar in C++ ? A quick look at the boost libraries didn't reveal something similar, which is quite surprising to me. Is it difficult to implement this functionality?

like image 373
ynimous Avatar asked Jun 11 '09 13:06

ynimous


1 Answers

Came across this question while investigating for a similar problem.

Even if the question is old, now in the time of C++ 11 and boost 1.54 it is pretty easy to do using the Boost.Range library. It features a join-function, which can join two ranges into a single one. Here you might incur performance penalties, as the lowest common range concept (i.e. Single Pass Range or Forward Range etc.) is used as new range's category and during the iteration the iterator might be checked if it needs to jump over to the new range, but your code can be easily written like:

#include <boost/range/join.hpp>  #include <iostream> #include <vector> #include <deque>  int main() {   std::deque<int> deq = {0,1,2,3,4};     std::vector<int> vec = {5,6,7,8,9};      for(auto i : boost::join(deq,vec))     std::cout << "i is: " << i << std::endl;    return 0; } 
like image 182
ovanes Avatar answered Sep 24 '22 08:09

ovanes