简体   繁体   中英

How do iterate through all sub vectors in a vector?

Lets say i have a class Foo. It contains a vector of type Foo. How can write a loop to iterate through the vector in foo and continually iterate through the sub vectors until we reach a level where on of the vectors is empty

class Foo
{
  Foo();
  std::vector<Foo> foos;
}

I can do this to iterate it through, but how can i iterate through the vectors in the foo objects inside the original vector recursively until i reach a level that the vector is empty?

Foo f;
if( !f->foos.empty() )
{

   std::vector<Foo>::const_iterator itr;

   for ( itr = f.foos.begin(); itr!=f.foos.end(); ++itr )
   {
   }
}

Use recursion:

class Foo
{
    Foo();
    std::vector<Foo> foos;

    void iterate()
    {
        std::vector<Foo>::const_iterator itr;

        for ( itr = foos.begin(); itr!=foos.end(); ++itr )
        {
            // do stuff  breadth-first
            (*itr).iterate();
            // do stuff  depth-first
        }
    }
}

Use a queue:

std::deque<Foo> q;
q.push_back(f);
while (!q.empty()) {
    Foo curr = q.back();

    typedef std::vector<Foo>::iterator iter;
    iter end = curr.foos.end();
    for(iter it = curr.foos.begin(); it != end; ++it) {
        if(!it->empty()) {
            q.push_back(*it);
            continue;
        }
        // do stuff with *it
    }

    q.pop_back();
}

Your Foo objects form a tree data structure. You can represent any path from root to some node as a std::stack<Foo*> to keep track of your position in the tree. Using this idea and a depth-first search, you can do your operation of visiting all of the Foo objects without using recursion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM