简体   繁体   English

如何遍历向量中的所有子向量?

[英]How do iterate through all sub vectors in a vector?

Lets say i have a class Foo. 可以说我有一堂课Foo。 It contains a vector of type Foo. 它包含一个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 如何编写一个循环来遍历foo中的向量并不断迭代子向量,直到我们达到向量on为空的级别

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对象中的向量,直到我达到向量为空的水平?

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. 您的Foo对象形成树数据结构。 You can represent any path from root to some node as a std::stack<Foo*> to keep track of your position in the tree. 您可以将任何从根到某个节点的路径表示为std::stack<Foo*>以跟踪您在树中的位置。 Using this idea and a depth-first search, you can do your operation of visiting all of the Foo objects without using recursion. 使用这个想法和深度优先搜索,您可以执行访问所有Foo对象的操作,而无需使用递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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