【问题标题】:Modifying pointers in std::vector with BOOST_FOREACH使用 BOOST_FOREACH 修改 std::vector 中的指针
【发布时间】:2013-04-12 09:08:31
【问题描述】:

我有一个班级node 并声明了一个std::vector<node*>。我想使用 BOOST_FOREACH 来迭代向量,但我遇到了一个小问题。

我的代码是这样的:

data_flow_graph* dfg;
node* other_node;

[...]

BOOST_FOREACH(node* n, vector_of_nodes){
  if (n->get_id() < 100)){
    n = new node(last_id++);
    n->add_related_node(other_node);
    dfg->add_node(n);
  }
}

这是,我尝试在迭代指针时修改指针的地址。问题是,虽然创建了新节点,但vector_of_nodes 中的指针保持不变。我想这是Boost如何管理对指针的访问的问题,因为如果我使用常规迭代器进行等效处理:

std::vector<node*>::iterator it;
std::vector<node*>::iterator et = vector_of_nodes.end();

for (it = vector_of_nodes.begin(); it != et; ++it){
  if ((*it)->get_id() < 100)){
    (*it) = new node(last_id++);
    (*it)->add_related_node(other_node);
    dfg->add_node(*it);
  }
}

代码运行良好,按预期运行。

我可以改用那个版本,但我很好奇……为什么第一个版本不起作用?

【问题讨论】:

标签: c++ boost boost-iterators


【解决方案1】:

修改代码

BOOST_FOREACH(node*& n, vector_of_nodes){
  if (n->get_id() < 100)){
    n = new node(last_id++);
    n->add_related_node(other_node);
    dfg->add_node(n);
  }
}

因为在您的版本中,您更改了本地指针的地址。而且,在使用n = new node 之前,为什么不删除旧的?既然手动管理资源有问题,为什么不用smart pointers

【讨论】:

  • 谢谢,它工作得很好。我不会删除旧节点,因为我需要将它保存在我的 dfg 中以备后用,因此旧节点仍然可以从其他地方看到。 :)
猜你喜欢
  • 2016-02-19
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
  • 2021-02-17
  • 2016-02-12
  • 2011-03-18
  • 1970-01-01
  • 2016-03-15
相关资源
最近更新 更多