在迭代地图时向/从地图添加/删除元素是否安全

时间:2014-01-08 13:24:00

标签: c++ linux map stl iterator

在迭代地图时,向此地图添加/删除元素是否安全?请参阅下面的伪代码:

       //Pseudo Code
       //test is a global variable
       map<int, CustomClass*> test;
       test[Index1] = new CustomClass;
       test[Index2] = new CustomClass;
       test[Index3] = new CustomClass;

       ... 
       //Iterating the map
       map<int, CustomClass*>::iterator itor;
       itor = test.begin();
       while(itor != test.end())
       {
            if (itor->first == IndexToRemove)
            {
                   //below function will remove 
                   //element from the map
                   RemoveFromMap(IndexToRemove);
            } 

            if (NeedAddNewElement())
            {
                   //below function will add
                   // an element to the map
                   AddNewElement(IndexToAdd);
            }

            itor++;
       }

       //Remove a mapping from map
       void RemoveFromMap(int index)
       {
            map<int, CustomClass*>::iterator itor;
            itor = test.begin();
            while(itor != test.end())
            {
                 if (itor->first == index)
                 {
                      test.erase(itor);
                      break;
                 }

                 itor++;
             }
        }

       //add new mapping to map
       void AddNewElement(int index)
       {
            //chech if index exists
            if (test.find(index) == test.end())          
             {           
                    test[index] = new CustomClass;           
             }
       }

2 个答案:

答案 0 :(得分:2)

迭代容器并擦除元素时,迭代器指向迭代器本身变得无效!

因此:

iterator = container.erase(iterator)

获取下一个有效的迭代器。

答案 1 :(得分:1)

operator[]不会使迭代器失效:

  

没有迭代器或引用无效。

但是erase使所有迭代器和对擦除元素的引用无效,而其他迭代器不受影响:

  

擦除元素的引用和迭代器无效。其他引用和迭代器不受影响。

在您的情况下,

擦除会返回Iterator following the last removed element.