1

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 クラスのの宣言を変更せずに、この非定数イテレータを作成する方法を探しています。

4

2 に答える 2

3

親は const イテレータです。したがってparent->second、 const です。parent->second.childrenしたがって、const です。したがって、parent->second.children.begin()const イテレータを返します。

erase非定数イテレータが必要です。

于 2012-08-20T11:27:04.297 に答える
0

erase()使用時はできませんconst_iterator。の目的は、要素を消去するなど、いかなる方法でもconst_iteratorの変更を禁止することです。vector単に使用してiteratorから、そのコンパイル エラーを修正する必要があります。

const_iterator次に、そのコンパイル エラーは、 a を非 constに割り当てようとしているために発生しますiteratorparent非 constを変更して作成するとiterator、エラーは解消されます。

于 2012-08-20T11:27:35.887 に答える