如何向向量添加元素并同时遍历它?

时间:2014-06-10 17:59:18

标签: c++ vector tree iterator breadth-first-search

我想在树上执行BFS,找出某个叶子,但是图形本质上是动态的,当我落在一片叶子上而那片叶子不是我要找的那片叶子时,那么它从叶子计算子元素(叶子不再是叶子,它是一个节点)。 enter image description here

我尝试了两种实现,都产生了错误的结果。我认为指针变得无效或者这是一个不正确的实现。我的代码如下

int y=0;
while(graph.end() - graph.begin() < 262145  and   graph.end() - graph.begin() < y){
        if(found(graph[y])){
            clock2 = graph[y];
            break;
        }
        else{
        if(graph[y].b[0] < 4) graph.push_back(move1(graph[y]));
        if(graph[y].b[1] < 4) graph.push_back(move2(graph[y]));

    }
    y++;
}

,下一个实现是这样的

for(vector<foo> :: iterator i = graph.begin();i!=graph.end();i++){
    if(found(*i)){
        clock2 = *i;
        break;
    }
    else{
        if(i->b[0] < 4) graph.push_back(move1(*i));//move1 and move2 are
        if(i->b[1] < 4) graph.push_back(move2(*i));//functions of return type foo
    }
}

这两个都导致程序崩溃。他们有什么问题,如何实施这些?请评论其他问题。

1 个答案:

答案 0 :(得分:0)

我有点困惑的是,到底发生了什么以及究竟是什么问题。但是如果你问如何在图形上预先形成一个简单的BFS,这里有一些我觉得很容易阅读的示例代码。

进一步评论,我会更改它以尝试匹配问题的确切标准(一旦我有更多的清晰度)

struct node{
   std::vector children<node*>;
   int data;
}
void bfs(node* root, int value){ // THIS IS CHECK FOR INTS so change for whatever value
    if(!root) return;
    std::queue myq;
    myq.push(root);
    node* toCheck;
    while(!myq.Empty()){
         toCheck = myq.top();
         myq.pop();
         if(toCheck->data == value){
              //do whatever you want with that information
         }else{
         /*
          //forloop/whileloop as many times as necessary to set all the new children
           //Example:
              node* newNode = new node();
              newNode->data = someValue; // just some information that you want to add
              toCheck->children.push_back(newNode);
         */
         }
         for(int i = 0; i < toCheck->children.size(); i++){
              myq.push(toCheck->children[i]);
         }
    }
}