{"id":599,"date":"2011-02-15T15:12:14","date_gmt":"2011-02-15T15:12:14","guid":{"rendered":"http:\/\/kera.name\/articles\/?p=599"},"modified":"2011-06-29T11:09:22","modified_gmt":"2011-06-29T11:09:22","slug":"tomalaks-tuesday-tip-10-how-to-iterate-erase-over-maps","status":"publish","type":"post","link":"https:\/\/kera.name\/articles\/2011\/02\/tomalaks-tuesday-tip-10-how-to-iterate-erase-over-maps\/","title":{"rendered":"Tomalak&#039;s Tuesday Tip #10: How to Iterate-Erase Over Maps"},"content":{"rendered":"<p>Keeping it low-key this week, let&#039;s re-iterate (lol) the conventional map-erase idiom in C++.<\/p>\n<p>Iterating through the elements of a <code>std::map<\/code> is easy enough, but complication arises when you want to delete a few elements as you go.<\/p>\n<p>The first naive approach might look a little like this:<\/p>\n<p><textarea name=\"code\" class=\"cpp:nocontrols:nogutter\" cols=\"60\" rows=\"10\">#include <map><\/p>\n<p>int main()\n{\ntypedef std::map<int, int> M;\ntypedef M::iterator        I;\nM m;\n\/<em> (populate m..) <\/em>\/<\/p>\n<pre><code>for (I it = m.begin(), end = m.end(); it != end; ++it) {\n   if (it->first == 3)\n      m.erase(it); \/\/ remove elements whose key is '3'\n}<\/code><\/pre>\n<p>}<\/textarea>\n<\/p>\n<p>Unfortunately, after you&#039;ve erased the element from the map, the iterator pointing to it is invalidated. When the loop goes to run <code>++it<\/code> ready for the next iteration, this invokes <a href=\"http:\/\/stackoverflow.com\/questions\/2766731\/what-exactly-do-ib-and-ub-mean\">UB<\/a>&#8230; meaning you should never do it. It&#039;s invalid.<\/p>\n<p>So what to do? If you do <code>++it<\/code> <em>before<\/em> performing the erase, then it&#039;s safe, but then you don&#039;t have the iterator to erase any more. You can use a copy:<\/p>\n<p><textarea name=\"code\" class=\"cpp:nocontrols:nogutter\" cols=\"60\" rows=\"10\">for (I it = m.begin(), end = m.end(); it != end; ) {\nif (it->first == 3) {\nM::iterator copy = it;\n++it; \/\/ increment ready for the next iteration\nm.erase(copy); \/\/ remove via original iterator\n}\nelse {\n++it; \/\/ just increment\n}\n}<\/textarea>\n<\/p>\n<p>Note the important change to the <em>for<\/em> declaration. The increment on each loop is replaced by the conditional increment in the body.<\/p>\n<p>A shorter version of the same thing is:<\/p>\n<p><textarea name=\"code\" class=\"cpp:nocontrols:nogutter\" cols=\"60\" rows=\"10\">for (I it = m.begin(), end = m.end(); it != end; ) {\nif (it->first == 3)\nm.erase(it++);\nelse\n++it;\n}<\/textarea>\n<\/p>\n<p>This works because <code>it++<\/code> inherently makes a copy, performing the increment <em>after<\/em> the original value is sent to <code>erase<\/code>, but before the erase actually occurs.<\/p>\n<p><b>Coming soon&#8230;<\/b><\/p>\n<p>Other standard containers make this a lot easier; the next C++ standard, due for completion this year (or possibly in 2012), will fix this omission for <code>std::map<\/code> by allowing <code>m.erase<\/code> to return the next iterator automatically:<\/p>\n<p><textarea name=\"code\" class=\"cpp:nocontrols:nogutter\" cols=\"60\" rows=\"10\">for (I it = m.begin(), end = m.end(); it != end; ) {\nif (it->first == 3)\nit = m.erase(it);\nelse\n++it;\n}<\/textarea><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Keeping it low-key this week, let&#039;s re-iterate (lol) the conventional map-erase idiom in C++.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[21,56,20,33],"_links":{"self":[{"href":"https:\/\/kera.name\/articles\/wp-json\/wp\/v2\/posts\/599"}],"collection":[{"href":"https:\/\/kera.name\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kera.name\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kera.name\/articles\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kera.name\/articles\/wp-json\/wp\/v2\/comments?post=599"}],"version-history":[{"count":14,"href":"https:\/\/kera.name\/articles\/wp-json\/wp\/v2\/posts\/599\/revisions"}],"predecessor-version":[{"id":608,"href":"https:\/\/kera.name\/articles\/wp-json\/wp\/v2\/posts\/599\/revisions\/608"}],"wp:attachment":[{"href":"https:\/\/kera.name\/articles\/wp-json\/wp\/v2\/media?parent=599"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kera.name\/articles\/wp-json\/wp\/v2\/categories?post=599"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kera.name\/articles\/wp-json\/wp\/v2\/tags?post=599"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}