正確使用stl map的erase方法

來源:互聯網
上載者:User

正確使用stl map的erase方法

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

eg:

map<string,string> mapTest;

typedef map<string,string>::iterator ITER;

ITER iter=mapTest.find(key);

mapTest.erase(iter);

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

但是當在一個迴圈裡用的時候,往往會被誤用,那是因為使用者沒有正確理解iterator的概念。

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

eg:

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

}

原文:

http://www.cppblog.com/abware/archive/2009/01/22/72459.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.