views:

80

answers:

2

Hello, I'm trying to define an iterator to iterate my map to erase it (destructor)
I'm getting an error : incompatible iterator.

My destructor looks like this :

Consortium<S,T>::~Consortium()  
{  
    map<const S, Node<T>*>::iterator deleteIterator;  
    for (m_consortiumMap.begin() ; deleteIterator != m_consortiumMap.end() ; deleteIterator++)  
      m_consortiumMap.erase(deleteIterator);  
}  

I create like this :

Consortium<string, Vehicle*> check;  

any suggestions?

+2  A: 

Use map<const S, shared_ptr<Node<T> > > instead.

fnieto
+1  A: 

Your immediate problem is that map<const S, Node<T>*>::iterator is a so-called dependent name: it is depends on the template arguments and, in theory, there could be a specialization of std::map for some S, T which defines iterator to be a static data member, the name of a member function or whatever. What it is, the compiler only finds out when instantiating your template. So you have to help the compiler by explaining to it that iterator is the name of a type. (Silly, I know, but compilers really are that stupid). You do it by putting a typename in front of it:

typename map<const S, Node<T>*>::iterator deleteIterator;

However, what you're actually doing is wrong. You don't need to manually delete the elements your map hosts. But.

You are using naked, dumb pointers as the map's referred type. Who owns these objects? Who is responsible for deleting them? You might have to go through your map and (instead of removing the pointers) delete the objects referred to by these pointers. But that's error prone, and still leaves open questions regarding the object's lifetime. (Like: Who takes responsibility for objects removed from the map?)
I strongly suggest you follow fnieto's advice and use a smart pointer instead.

sbi