Question

I have a class node and declared a std::vector<node*>. I would like to use BOOST_FOREACH to iterate the vector, but I'm having a little problem.

My code is like this:

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

This is, I try to modify the address of the pointer while iterating over it. The problem is that, although the new nodes are created, the pointers in vector_of_nodes remain unchanged. I guess it is a problem of how Boost manage the access to the pointers, because if I do an equivalent processing using regular iterators:

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

The code works well, and does as intended.

I could use that version instead, but I am curious... Why doesn't the first version work?

Was it helpful?

Solution

Change code to

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

since in your version you change address of local pointer. And, before you use n = new node, why you don't delete old? Since you have problems with manual managing of resources, why you don't use smart pointers?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top