Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do iterate through all sub vectors in a vector?

Tags:

c++

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 )
   {
   }
}
like image 754
Bullsfan127 Avatar asked May 22 '13 15:05

Bullsfan127


1 Answers

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
        }
    }
}
like image 100
Exceptyon Avatar answered Nov 14 '22 21:11

Exceptyon