std::map在遍历的过程中删除item的最好方式

xiaoxiao2021-02-28  97

看到了一种新的方法:

#include <map> #include <string> void erase_1()//以前都是用的这个笨方法. { std::map<int, int> cache; for (int i = 1; i < 10; ++i) cache[i] = i * 10; //在遍历的过程中删除某个节点 for (bool reSerarch = true; reSerarch;) { reSerarch = false; for (auto itr = cache.begin(); itr != cache.end(); ++itr) { if (itr->first == 6) { cache.erase(itr); reSerarch = true; break; } } } return; } void erase_2()//在看了某同事的代码后,发现,竟然还有这种操作,-_-! { std::map<int, int> cache; for (int i = 1; i < 10; ++i) cache[i] = i * 10; //在遍历的过程中删除某个节点 for (auto itr = cache.begin(); itr != cache.end(); ++itr) { if (itr->first == 6) { itr = cache.erase(itr); } } /* C++11 (1) iterator erase (const_iterator position); (2) size_type erase (const key_type& k); (3) iterator erase (const_iterator first, const_iterator last); */ return; } int main() { erase_1(); erase_2(); return 0; }完。

转载请注明原文地址: https://www.6miu.com/read-24016.html

最新回复(0)