samedi 25 juin 2016

Reasonable ways to implement depth-first iterator for a hierarchical (nested) data structure?

I have a data structure that boils down to nested containers:

struct ComplexContainer {
   struct Item {};
   std::vector<std::vector<std::vector<Item>>> _containerMadness;
}

Now I want to implement a depth-first forward iterator. My initial idea was:

struct const_iterator {
        const_iterator& operator++();
        const IndexedFragment& operator*() const;

private:
    std::vector<std::vector<std::vector<Item>>>::const_iterator _lvl1Iterator;
    std::vector<std::vector<Item>>::const_iterator _lvl2Iterator;
    std::vector<Item>::const_iterator _lvl3Iterator;
};

But then operator++ is way too difficult to implement because it's not guaranteed than level 1 container is not empty, in which case lvl 2 and lvl 3 don't even exist. Similarly, lvl 2 container may exist but be empty. Since std::vector::iterator doesn't hold a user-accessible reference to its container, I don't see a simple way to check for that (there's no iterator.valid() or some such). I understand that it can be implemented with all the sanity checking, but I don't like the code it results in - neither its structure nor the amount.

There must be a neat way to do this!

Aucun commentaire:

Enregistrer un commentaire