【问题标题】:How to add elements to a vector and traverse it simultaneously?如何将元素添加到向量并同时遍历它?
【发布时间】:2014-06-10 17:59:17
【问题描述】:

我想在一棵树上执行 BFS,找出某一片叶子,但该图本质上是动态的,当我落在一片叶子上并且那片叶子不是我要找的那片叶子时,它的子节点是从叶子计算(叶子不再是叶子它是一个节点)。

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

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
    }
}

这两种情况都会导致程序崩溃。他们有什么问题,如何实施这些?如有其他疑问,请发表评论。

【问题讨论】:

  • 你不能使用向量,因为某些插入可能会使迭代器无效,比如当大小超过容量时。
  • 在第一个 sn-p 中,这看起来不对:graph.end() - graph.begin() &lt;= y
  • 这是什么神奇的数字? graph.end() - graph.begin()
  • 这是树的最大允许大小...准确地说是 4^9 +1

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


【解决方案1】:

我也有点困惑到底发生了什么,你到底在问什么。但是,如果您要问如何在图表上执行简单的 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]);
         }
    }
}

【讨论】:

  • 我已经编辑了我的问题。看看你现在是否能更好地理解
  • 等等,树还没有制作好?您决定在什么条件下制作更多节点?多少个节点?树已经平了吗? (已经在向量中)?即不需要处理左/右只穿过向量?
  • 树尚未生成。当当前节点不是我要搜索的节点时,我会添加更多节点。即假设我正在尝试猜测密码(为了不必绘制很多分支,让我们考虑它是二进制的)我会这样做。是0,是吗?美好的。不?是 1. 是吗?美好的。不?是 00 吗?是的 。美好的。不?是01吗?并因此...
  • 而且@Jay 看在上帝的份上,它不是二叉树......每个节点最多可以有 9 个孩子。
  • 嘿伙计,它是否是二叉树并不重要。二叉树是图的子集。我只是用它作为例子。我修复了代码。告诉我我是否更正确。
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-11
  • 2021-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多