1

Here's C++ code. I'm confused as to why dereferencing the iterator tells me the variable is read only? It's a public member of the Node class. What is my error?

adjTable is a set of Node elements -see declarations below.

Cells::iterator pos = adjTable.find(*thisNode);
if (pos == adjTable.end()) { // Did we find it?
    NSLog(@"Not found");
// What to do here if node not found
}
// We found the node - mark it as grey in the table
(*pos).colour = grey; // <<<<<<<< this is the line with the issue

Here are the declarations etc.(it doesn't seem to format correctly)

class Node { // Define a single node a.k.a. matrix cell
public:
    short nodeID;           // the tag from the cell
    short colour;           // for tri-colour used in traversing
    std::vector<short>adjs; // nodeIDs of adjacent nodes

    // Ctors
    Node(){};
    Node(short ID, short col, std::vector<short>adjs)
        : nodeID(ID), colour(col), adjs(adjs){}
    // Dtors
    ~Node(){};
    // operators
    bool operator<(const Node& rhs) const{
        return nodeID < rhs.nodeID;
    }
    bool operator==(const Node& rhs) const{
        return nodeID == rhs.nodeID;
    }
};

typedef std::set<Node,SortNodeSet> Cells;
class MakeTable {
public:
    MakeTable(){};
    ~MakeTable(){};
    Cells makeTable();
};
L84
  • 45,514
  • 58
  • 177
  • 257
pteeson
  • 11
  • 1
  • 3
  • Additional SO info regarding `std::set` modifications http://stackoverflow.com/questions/908949/what-happens-when-you-modify-an-element-of-an-stdset – txtechhelp Feb 09 '14 at 23:00
  • This link helped me. I chose to use const_cast((*pos).colour) = grey; – pteeson Feb 10 '14 at 20:58

3 Answers3

1

The elements of an std::set are immutable. So you cannot modify them. If you want to be able to modify them, you need a different data structure.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

Changing the key for a map or set may lead to undefined behavior as your map/set depends on the key values to maintain order. If your SortNodeSet function/functor does not use the colour field, which is likely and a logical choice in graph algroithms, you can define this field as a mutable field,i.e.

mutable short colour;

This tells the compiler that a Node isn't considered changed if you change the colour field.

thor
  • 21,418
  • 31
  • 87
  • 173
0

Since your comparison is based only on ID, you might want to use a std::map<short, Node> to enable ID-based lookup.

Then, make the nodeID member variable const, since changing the ID will break the lookup.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720