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?
Ok, so this isn’t a full solution – but I ran out of time. So this currently implements not a full iterator but a cut down iterator-like class which defines something like this interface, and requires C++11. I’ve tested it on g++4.7:
Where
NestedContainerTypeis the nested container type (surprisingly), and Terminator is the type of the innermost thing that you’re wanting to get out of the flatten.The code below works, but this is certainly not extensively tested. Wrapping it up fully (assuming you’re happy with forward advance only) shouldn’t be too much work, in particular if you use
boost::iterator_facade.And with the following test cases, it does what you would expect:
So prints the following for each of the container types:
Note that it doesn’t yet work with
sets because there’s some foo required to deal with the fact thatsetiterators return const references. Exercise for the reader… 🙂