Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten iterators of nested containers?

Tags:

c++

iterator

This is (yet) a(nother) follow up to James' answer to this question: Flattening iterator

How do I alter the flattenig_iterator such that it works recursively? Say I have more levels of nested containers and I don't want to be limited to a given nesting depth. I.e. flattening_iterator should work with

std::vector< std::vector < std::vector < int > > >

as well as with

std::vector< std::vector < std::vector < std::vector < int > > > >

In my actual code I have an array of objects which might or not contain such an array themselves.

edit:

After playing around with different ways of iterating through different kind of nested containers I learned something that might be interesting to others as well:

Accessing the container elements with nested loops executed 5 to 6 times faster than with the iterator solution.

Pros:

  • elements can be complex objects, e.g. (like in my case) classes that contain containers.
  • faster execution

Cons:

  • Each container structure requires a new implementation of the loop
  • standard library algorithms are not available

Other pros and cons?

like image 349
steffen Avatar asked Jul 12 '12 15:07

steffen


1 Answers

I'll quickly outline a solution:

  1. Write a is_container trait that detects begin() and end() members, or possibly some more complex rules;
  2. Write a all_flattening_iterator<T> template that is just a flattening_iterator<all_flattening_iterator<typename T::value_type>>;
  3. Write a specialization of all_flattening_iterator<T> for when T is not a container (use a default template bool parameter) that is just a regular iterator.
like image 155
R. Martinho Fernandes Avatar answered Sep 23 '22 08:09

R. Martinho Fernandes