How can a C++ object have as a member an iterator to its position in an std::list?

199 views Asked by At

I have an application where I have nodes that have connections to eachother. Each node stores a list of incoming and outgoing connections to the other nodes. From time to time the receiving node needs to be able to get rid of one of its incoming connections. When this happens, I want the connection to be removed from not only the receiving node's list of incoming connections, but also from the sending node's list of outgoing connections. But in order to do this, the receiving node needs the sending node's iterator for the connection. It would be nice if I could just store that iterator as a member of the connection object. But trying to do this will not even compile. When I try to declare an iterator as a class member, the compiler tells me that it is an undefined type. This is what my class declaration looks like:

class Connection
{
   public:
   Connection();
   ~Connection();

   Node* pSourceNode;
   std::list<Connection*>::iterator SourcesIterator;
};

Is there any neat way to make this or something like it work without having to write my own linked list? Perhaps some data structure that has thus far eluded me?

2

There are 2 answers

3
James On

I was able to compile your code just fine. Are you doing a #include <list> in the header?

You may not wish to keep around the iterator anyway; a large number of operations invalidate them. You could keep a pointer to the list in question and get a new iterator when needed.

2
Ben Voigt On

You might try a typedef/forward declaration combination, might work better in VC6:

typedef class Connection* ConnectionPtr;
class Connection
{
   public:
   Connection();
   ~Connection();

   Node* pSourceNode;
   std::list<ConnectionPtr>::iterator SourcesIterator;
};