I'm experiencing a problem using the erase function in C++.
I have the following structure:
typedef std::map<std::string,TreeElement> ObjMap;
class TreeElement {
public:
ObjMap::const_iterator parent;
std::vector<ObjMap::const_iterator > children;
}
Now I'm trying to remove a TreeElement from the list of children of its parent using the erase function.
//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
This gives an error during compilation indicating it can't convert
__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> > > >
to
__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> > > >
Is there any way to fix this? I tried using an iterator instead of a const_iterator but this just moved the compilation error to
std::vector<SegmentMap::const_iterator >::iterator it = parent->second.children.begin();
Clarification: I know the erase function expects a non-const iterator. I'm looking for a way to create this non-const iterator without changing the declaration of parent and children in the TreeElement class.
Parent is const iterator, therefore parent->second
is const, therefore parent->second.children
is const, therefore parent->second.children.begin()
returns const iterator.
erase
expects a non-const iterator.