映射擦除错误

时间:2012-03-15 11:53:22

标签: c++ map erase

我在地图上有不同的操作程序。

以下是我程序的示例代码。

在运行此代码时,我收到一个错误,例如地图擦除超出范围异常。

请帮我解决这个问题。

  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();
  }

3 个答案:

答案 0 :(得分:2)

您正试图删除位于之前第一个元素的元素,这指向什么?


发布代码的相关摘录:

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

附注是我发现您能够编译并运行提供的代码段非常奇怪。

如果您无法通过std::map<int,int>::const_iterator m1_cIter的类型删除元素,则会给您错误。

答案 1 :(得分:1)

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

是未定义的行为。你的意思是

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

答案 2 :(得分: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--;

这可能是未定义的行为,不能保证始终有效。