【问题标题】:map erase error地图擦除错误
【发布时间】:2026-02-07 04:50:01
【问题描述】:

我为地图上的不同操作编写了程序。

下面给出了我的程序的示例代码。

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

请帮我解决这个问题。

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

【问题讨论】:

  • 您应该尝试在您的代码中添加一些调试couts 以帮助追踪您的问题。我们通常不会为您调试代码。找出问题,然后提出问题。
  • 我在这部分遇到运行时错误 m1_cIter = m1.begin( ); m1_cIter--; m1.erase ( m1_cIter );

标签: c++ map erase


【解决方案1】:

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


发布代码中的相关sn-p:

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

附注是我觉得很奇怪你竟然能够编译和运行提供的 sn-p。

它应该会给你错误,因为你不能通过std::map&lt;int,int&gt;::const_iterator 擦除元素,这是m1_cIter 的类型。

【讨论】:

  • @0A0D 但不是const_iteratorconst_iterator 应该/不能用于修改容器内的元素。
  • 是的,但有一个解决方法。这是语言本身的缺陷。 *.com/questions/4885318/…
【解决方案2】:
m1_cIter = m1.begin();
m1_cIter --;

是未定义的行为。你是说

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】: