简体   繁体   English

如何在模板中定义迭代器?

[英]How to define an iterator in a template?

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? 有什么建议么?

请改用map<const S, shared_ptr<Node<T> > >

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. 您的直接问题是map<const S, Node<T>*>::iterator是所谓的从属名称 :它取决于模板参数,理论上, std::map可以专门用于一些STiterator定义为静态数据成员,成员函数的名称或其他名称。 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. 因此,您必须向编译器解释iterator是类型的名称,以帮助编译器。 (Silly, I know, but compilers really are that stupid). (很傻,我知道,但是编译器确实如此愚蠢)。 You do it by putting a typename in front of it: 您可以通过把一个做typename在它的前面:

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. 我强烈建议您听fnieto的建议 ,改用智能指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM