2012-03-15 16 views
0

私はマップ上で異なる操作のためにwriittenプログラムを持っています。マップ消去エラー

私のプログラムのサンプルコードは以下の通りです。

このコードを実行しているうちに、マップの範囲外の例外のようなエラーが発生しています。

私はこれを解決するのを手伝ってください。

int main() 
    { 
    using namespace std; 
    map <int, int> m1; 

    map <int, int> :: iterator m1_Iter; 
    map <int, int> :: const_iterator m1_cIter; 
    typedef pair <int, int> Int_Pair; 

    m1.insert (Int_Pair (1, 10)); 
    m1.insert (Int_Pair (2, 20)); 
    m1.insert (Int_Pair (3, 30)); 

    m1_cIter = m1.end(); 
    m1_cIter--; 
    cout << "The value of the last element of m1 is:\n" 
     << m1_cIter -> second << endl; 

    m1_Iter = m1.end(); 
    m1_Iter--; 
    m1.erase (m1_Iter); 

      m1_cIter = m1.begin(); 
    m1_cIter--; 
    m1.erase (m1_cIter); 

    m1_cIter = m1.end(); 
    m1_cIter--; 
    cout << "The value of the last element of m1 is now:\n" 
     << m1_cIter -> second << endl; 
    getchar(); 
    } 
+0

問題をトレースするのに役立つコードにデバッグ用の 'cout'を追加してください。私たちは通常あなたのためにコードをデバッグしません。問題を特定し、質問します。 –

+0

この部分に実行時エラーが発生しました。 m1_cIter = m1.begin(); m1_cIter--; m1.erase(m1_cIter); –

+0

http://stackoverflow.com/questions/4885318/calling-erase-with-iterator-vs-const-iterator –

答えて

2

あなたはあなたの最初の要素の前を設置要素を消去しようとしている、何この点をでしょうか?投稿コードから


関連スニペット:

m1_cIter = m1.begin(); 
m1_cIter--; 
m1.erase (m1_cIter); 

サイドノートは、私はあなたがすべてで提供スニペットをコンパイルして実行することができること、それは非常に奇妙な発見だということです。

のタイプのstd::map<int,int>::const_iteratorで要素を消去できないという事実に関するエラーが表示されます。

+0

イレーズは反復子をとります... –

+0

@ 0A0D、しかし 'const_iterator'はありません。 'const_iterator'は、コンテナ内の要素を変更するために使うべきです。 –

+0

はい、回避策があります。それは言語自体の欠陥です。 http://stackoverflow.com/questions/4885318/calling-erase-with-iterator-vs-const-iterator –

1
m1_cIter = m1.begin(); 
m1_cIter --; 

は未定義の動作です。あなたはm1_cIterconst_iteratorあるので、これは問題になる可能性が

m1_cIter = m1.end(); 
m1_cIter --; 
0

m1.erase (m1_cIter);

を意味しました。コードはコンパイルされません。あなたのコードでも

./maptest 
The value of the last element of m1 is: 
30 
The value of the last element of m1 is now: 
20 

m1_cIter = m1.begin(); 
m1_cIter--; 

これは常に動作する保証はありません未定義の動作である可能性があり

は、この行をコメントした後、私はこの出力を取得します。