[英]C++: Using erase in a vector of iterators
我在使用C ++中的擦除功能时遇到了问题。
我有以下结构:
typedef std::map<std::string,TreeElement> ObjMap;
class TreeElement {
public:
ObjMap::const_iterator parent;
std::vector<ObjMap::const_iterator > children;
}
现在我正在尝试使用erase函数从其父级子级列表中删除TreeElement。
//Remove from parent
SegmentMap::const_iterator parent = segment->second.parent;
std::vector<SegmentMap::const_iterator >::const_iterator it = parent->second.children.begin();
for(;((*it)->first != segment->first) && (it != parent->second.children.end()); it++);
parent->second.children.erase(it); //Compilation fails
这在编译期间出现错误,表明它无法转换
__gnu_cxx::__normal_iterator<const std::_Rb_tree_const_iterator<std::pair<const std::basic_string<char>, TreeElement> >*, std::vector<std::_Rb_tree_const_iterator<std::pair<const std::basic_string<char>, TreeElement> > > >
至
__gnu_cxx::__normal_iterator<std::_Rb_tree_const_iterator<std::pair<const std::basic_string<char>, TreeElement> >*, std::vector<std::_Rb_tree_const_iterator<std::pair<const std::basic_string<char>, TreeElement> > > >
有没有什么办法解决这一问题? 我尝试使用迭代器而不是const_iterator,但这只是将编译错误移到了
std::vector<SegmentMap::const_iterator >::iterator it = parent->second.children.begin();
澄清:我知道erase函数需要一个非const迭代器。 我正在寻找一种方法来创建这个非const迭代器,而无需更改TreeElement类中的父和子的声明。
Parent是const迭代器,因此parent->second
是const,因此parent->second.children
是const,因此parent->second.children.begin()
返回const迭代器。
erase
需要一个非const迭代器。
使用const_iterator
时不能执行erase()
。 const_iterator
的目的是禁止以任何方式修改vector
,包括通过它擦除元素。 您应该使用简单的iterator
,然后修复该编译错误。
然后编译错误是因为您尝试将const_iterator
分配给非const iterator
。 如果修改并使parent
成为非const iterator
,则错误应该消失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.