c++ 遍歷map的時候刪除元素

在c++編程的時候,我們有時會遇到,在遍歷map的時候,刪除符合某個條件的元素,如果我們不做任何處理,直接刪除map元素的話,程序會異常終端,提示"Expression: map/set iterator not incrementable"。所以如果想在遍歷map的時候刪除元素,必須做一些處理,下面給出一種方法.

#include <iostream>

#include <map>

using namespace std;





int main()

{

    map<int, int> test_map;

    test_map[1] = 1;

    test_map[2] = 2;

    test_map[3] = 3;

    test_map[4] = 4;

    

    for( std::map<int, int>::iterator iter = test_map.begin();

        iter != test_map.end(); ++ iter )

    {

        cout << iter->first << " " << iter->second << endl;

    }

    

    int count = 0;

    

    // delete the element

    for( std::map<int, int>::iterator iter = test_map.begin();

        iter != test_map.end(); )

    {

        std::map<int, int>::iterator it_back = iter;

        bool is_first_element = false;

        if(it_back != test_map.begin())

        it_back --;

        else

        is_first_element = true;

        

        // delete the element that matches the specific condition

        if( iter->first % 2 == 0)

        {

            test_map.erase(iter);

            

            if(is_first_element)

             iter = test_map.begin();

            else

                iter = ++ it_back;

        }else iter ++;      

        

        count ++;

    }

    

    cout << "use count:" << count << endl;

    

    cout << "after delete " << endl;

    

    for( std::map<int, int>::iterator iter = test_map.begin();

        iter != test_map.end(); ++ iter)

    {

        cout << iter->first << " " << iter->second << endl;

    }

    

    system("pause");

    return 0;

     

}


 

運行結果

  1. 1 1
  2. 2 2
  3. 3 3
  4. 4 4
  5. use count:4
  6. after delete
  7. 1 1
  8. 3 3

 

 

 

遍歷所需次數,也就是整個map的總元素個數,不會增加額外的次數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章