map的erase函式小結
阿新 • • 發佈:2020-10-09
關於map關聯容器的刪除c++ primer只是一筆帶過,實際上不了解去使用還是有點問題,比如所以for去遍歷刪除指定條件的節點就有坑;索性去c++官網看例子,連結如下
http://www.cplusplus.com/reference/map/map/erase/
https://en.cppreference.com/w/cpp/container/map/erase
std::map<char, int> mymap; std::map<char, int>::iterator it; // insert some values: mymap['a'] = 10; mymap['b'] = 20; mymap['c'] = 30; mymap['d'] = 40; mymap['e'] = 50; mymap['f'] = 60; it = mymap.find('b'); it= mymap.erase(it); // erasing by iterator mymap.erase('c'); // erasing by key it = mymap.find('e'); auto it2 = mymap.find('f'); it2 = mymap.erase(it, it2); // erasing by range // show content: for (it = mymap.begin(); it != mymap.end(); ++it) std::cout << it->first << " => " << it->second << '\n';
//寫一個測試的遍歷刪除例子 for (auto it = mymap.begin(); it != mymap.end();) { if (it->second == 20) { it = mymap.erase(it); } else { ++it; } }
總結:
map的刪除函式有三種形式,1.刪除給定iterator指定的那個位置;2.刪除[first,last)迭代器區間的所以節點(記得是前閉後開區間),3.刪除給定key的節點
1和2的返回值是指向被刪除元素的下一個元素的迭代器(所以如果是區間刪除是指向last,呵呵),3返回的是刪除元素的個數