C++ 中經常使用的容器類有vector,list,map。其中vector和list的erase都是返回迭代器,但是map就比較不一樣。
當在循環體中使用map::erase語句時,為了能夠在任何機器上編譯通過,並且能夠跨平台(windows、linux),正確的寫法是:
map<int, int> l_map; map<int, int>::iterator l_iter = l_map.begin(); map<int, int>::iterator l_iterErase; while (l_iter != l_map.end()) { l_iterErase = l_iter; l_iter++; l_map.erase(l_iterErase); }
也有人提出了這樣的寫法:
map<int, int> l_map; map<int, int>::iterator l_iter = l_map.begin(); while (l_iter != l_map.end()) { l_map.erase(l_iter++); }
這個寫法據某牛人說,只適合參數入棧順序是從右向左的方式,參數入棧順序是和具體編譯器實現相關的。也就是,如果不幸遇到參數入棧順序是從左向右的,上面的寫法就不行了。
上面是牛人的說法,但是我想不通的是,只有一個參數的時候,參數入棧順序應該沒有影響啊?
關於函數參數中帶++,--運算符的文章請見: i++和++i作為參數時的編譯器處理方式分析~
正確使用stl map的erase方法
先聲明:下面的文章是針對windows的用法,因為std::map的erase函數的windows的實現版本是返回一個std::map的迭代器,但是STL標准里面的該函數的返回值確是:
map.erase有3個重載,不同的C++版本標准其erase函數也不同:
- C++98(1998/2003 Standard)
void erase (iterator position); size_type erase (const key_type& k); void erase (iterator first, iterator last);
- C++11(2011 Standard)
iterator erase (const_iterator position); size_type erase (const key_type& k); iterator erase (const_iterator first, const_iterator last);
所以下面的代碼中的最后一個例子僅僅可以在windows下的map下運行。
STL的map表里有一個erase方法用來從一個map中刪除掉指令的節點
eg1:
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); }