C++11: Is it safe to remove individual elements from std::unordered_map while iterating?

前端 未结 1 1671
执念已碎
执念已碎 2021-02-18 21:50

Consider the canonical algorithm for removing an element from an associative container while iterating:

for (auto iter = myMap.begin(); iter != myMap.end(); )
{
         


        
相关标签:
1条回答
  • 2021-02-18 21:59

    Edit: The dangers of NoScript. I had noscript running, which displayed the C11 and C14 tabs as one box. Praetorian's answer is correct about it being guaranteed in practice, and formalized in c14.

    ** Below is wrong due to noscript.

    At the bottom of cplusplus it states that

    Only the iterators and references to the elements removed are invalidated.

    The rest are unaffected.

    The relative order of iteration of the elements not removed by the operation is preserved.

    http://www.cplusplus.com/reference/unordered_map/unordered_map/erase/

    At the top of the page, it states it's for C++11...so unless they updated it for C++14, i think it applies to C++11 as well. Praetorian should put an answer and you should check his for the answer, because even if it's not guaranteed in the standard for C++11 (C++14 being the patch for these sort of things), it's guaranteed in practice.

    I couldn't find the STL standard, I seem to have misplaced it, or I'd go see if there was a text guaranteed I could point to. :-/

    0 讨论(0)
提交回复
热议问题