C++:在迭代器的向量中使用擦除

C++: Using erase in a vector of iterators

本文关键字:擦除 向量 迭代器 C++      更新时间:2023-10-16

我在C++中使用擦除函数时遇到问题。

我有以下结构:

typedef std::map<std::string,TreeElement> ObjMap;
class TreeElement {
    public:
        ObjMap::const_iterator parent;
        std::vector<ObjMap::const_iterator > children;
}

现在,我正试图使用擦除函数将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();

澄清:我知道擦除函数需要一个非常量迭代器。我正在寻找一种方法来创建这个非常量迭代器,而不更改TreeElement类中parentchildren的声明。

Parent是const迭代器,因此parent->second是const,因此parent->second.children是const。因此parent->second.children.begin()返回const迭代器。

erase需要一个非常数迭代器。

使用const_iterator时不能执行erase()const_iterator的目的是禁止以任何方式修改vector,包括通过它擦除元素。您应该简单地使用iterator,然后修复编译错误。

那么编译错误是因为您试图将const_iterator分配给非常量iterator。如果修改parent并使其成为非常数iterator,则错误应该会消失。