2012-03-15 70 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--; 

这可能是不确定的行为,不能保证总是工作。