C++:在迭代器的向量中使用擦除
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;
}
现在,我正试图使用擦除函数将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类中parent和children的声明。
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
,则错误应该会消失。
相关文章:
- 为什么我的向量::擦除调用会抛出"vector subscript out of range"?
- 分割错误:向量中的擦除功能
- 如何使用擦除和迭代器来删除二维向量中的项目
- 从向量和对向量中擦除元素的差异
- 如何将某个元素从shared_ptr擦除到对象向量?
- 如何根据某些值擦除/删除类对象的向量
- 给定一个向量,擦除低于 itemsnum 的元素
- C++ 向量::使用类对象迭代器擦除不擦除向量成员
- C 矢量元素擦除与新向量创建
- 从向量中擦除元素是否也会擦除元素中存在的所有成员向量
- 向量擦除功能无法正常工作
- 使用迭代器时遇到问题,每 M 次传递一次擦除一个向量项
- 如何更有效地从向量或集合中擦除元素?
- 插入排序与插入/擦除?(所以我需要对一个向量进行排序,而不是手工做事,而是使用插入和擦除
- 使用擦除-删除范例将元素从一个向量移动到另一个向量
- 当我在c++中擦除向量时,我遇到了双自由错误
- 用算法擦除向量中的特定元素
- 在这种情况下如何擦除向量元素
- 如何擦除向量的一部分
- 如何查找和擦除向量元素中的某个字符