roro
roro

Reputation: 177

C++ How to update member value via map value pointers

I have an unusual graph structure that's made up of a few classes, and I'm trying to set a boolean member value in one of them for the sake of traversal. Let's say the classes are Graph, Node, and Edge. Graph holds an unordered map with string labels as keys and Nodes as values. The graph has bounded degree, so fixed sized arrays of pointers to Edges are kept at each node, and each Edge also has pointers to the Nodes at each end.

My aim is to visit every Edge once, so I maintain a boolean 'marked' flag inside every Edge initially set to false. Since the map in the Graph lets me iterate over Nodes, I wish to iterate over all Edges from every Node and mark each to avoid repeated visits from opposite ends. However, I find that the marks are failing to be recorded and can't seem to get it to work.

My iteration code looks like this:

for(auto it = nodeMap.begin(); it != nodeMap.end(); ++it){
    Node* node = &it->second;
    for (i=0; i< node->EdgeArray.size(); i++){
        if (node->EdgeArray[i]){
            Edge & edge = *(node->EdgeArray[i]);
            if(edge.getMark()) continue;
            [...do needed processing...]
            edge.setMark(true);
        }
    }
}

I am more comfortable with pointers than I am with references, so my original version had 'edge' as a pointer into EdgeArray without the dereferencing. However, some digging led me to understand that passing by reference is used to effect changes on function caller's values. My suspicion was that some kind of similar tweak is needed here, but in this case all of the iteration occurs in a method in the Graph class where the nodeMap is stored. I've tried basically all variations of pointers (dereferenced or not) and references I could think of, but can't seem to get the marked values to persist outside the loop. I.e., if I add a print that depends on the second if conditional, I never see a result from it.

Upvotes: 0

Views: 78

Answers (1)

cbuchart
cbuchart

Reputation: 11555

If your previous version worked, have you tried replacing only edge.setMark(true) with node->EdgeArray[i]->setMark(true)?

Upvotes: 1

Related Questions