天天看點

STL中Map的erase函數

STL的map表裡有一個erase方法用來從一個map中删除掉指令的節點

eg1:

#include <map>
using namespace std;
map<string,string> mapTest;
typedef map<string,string>::iterator ITER;

ITER iter=mapTest.find(key);
mapTest.erase(iter);      

 像上面這樣隻是删除單個節點,map的形為不會出現任務問題,

但是當在一個循環裡用的時候,往往會被誤用,那是因為使用者沒有正确了解iterator的概念.

像下面這樣的一個例子就是錯誤的寫法,

eg2:

for(ITER iter=mapTest.begin();iter!=mapTest.end();++iter)
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter);
}      

這是一種錯誤的寫法,會導緻程式行為不可知.究其原因是map 是關聯容器,對于關聯容器來說,如果某一個元素已經被删除,那麼其對應的疊代器就失效了,不應該再被使用;否則會導緻程式無定義的行為。

可以用以下方法解決這問題:

正确的寫法

1.使用删除之前的疊代器定位下一個元素。STL建議的使用方式

for(ITER iter=mapTest.begin();iter!=mapTest.end();)
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter++);
}      

2. erase() 成員函數傳回下一個元素的疊代器

for(ITER iter=mapTest.begin();iter!=mapTest.end();)
{
cout<<iter->first<<":"<<iter->second<<endl;
iter=mapTest.erase(iter);
}      

3.當想删除部分元素時,如下操作:

#include<map>
using namespace std;
for(ITER iter=mapTest.begin();iter!=mapTest.end();)
{
if(NeedErase(iter))
  iter=mapTest.erase(iter);
else
  iter++;
}      

這種方法對所有的容器類型都适用!

轉載于:https://www.cnblogs.com/fushi/p/7895588.html