2012-03-15 48 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'來幫助追查您的問題。我們通常不會爲您調試您的代碼。找出問題,然後提出問題。 – 2012-03-15 12:01:42

+0

我在這部分得到運行時錯誤 m1_cIter = m1.begin(); m1_cIter--; m1.erase(m1_cIter); – 2012-03-15 12:07:10

+0

http://stackoverflow.com/questions/4885318/calling-erase-with-iterator-vs-const-iterator – 2012-03-15 12:34:09

回答

2

您正在嘗試之前你的第一個元素抹去位於元素,會是什麼這一點?


從發佈代碼相關片段:

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

一個側面說明的是,我發現這很奇怪,你能在所有的編譯和運行提供片段。

它應該給你錯誤的事實,你不能通過std::map<int,int>::const_iterator,這是m1_cIter類型擦除元素。

+0

擦除需要迭代器.... – 2012-03-15 12:21:09

+0

@ 0A0D但不是'const_iterator'。 'const_iterator'應該/不能用來修改容器內的元素。 – 2012-03-15 12:23:00

+0

是的,但有一個解決方法。這是語言本身的缺陷。 http://stackoverflow.com/questions/4885318/calling-erase-with-iterator-vs-const-iterator – 2012-03-15 12:30:48

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

是未定義的行爲。您的意思是

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

m1.erase (m1_cIter);

這可能是問題,因爲m1_cIterconst_iterator。代碼不會編譯。

評論這條線之後,我得到這樣的輸出:

./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--; 

這可能是不確定的行爲,不能保證總是工作。