Home > Blockchain >  Insertion and Deletion of Multiset Elements while Traversing through for loop using iterators
Insertion and Deletion of Multiset Elements while Traversing through for loop using iterators

Time:12-21

Here, I am performing erase operations and an insert operation on the multiset while traversing through the multiset. The Code that I have written is:

#include <bits/stdc  .h>

using namespace std;

int main(){
    multiset<int> ms;
    ms.insert(6);
    ms.insert(7);
    ms.insert(8);
    ms.insert(9);
    ms.insert(10);
    for(auto it = ms.begin();it != ms.end();it  ){
        cout << *it << endl;
        ms.erase(it);
        if(*it == 6){
            ms.insert(4);
        }
    }
}

Output of the Above Code is : 6 7 4 8 9 10

I am unable to understand the output and how 4 is printing as a part of output!!

Does anyone know the explanation to the output???

I have tried different insertion and deletion operations on set while traversing through the for loop using iterators. Always getting stuck at some point and unable to understand the output!!

CodePudding user response:

As you can see in the multiset::erase documentation:

References and iterators to the erased elements are invalidated

Therefore after this line:

ms.erase(it);

Any attempt to derefrence it (like you do in the next line with *it) is UB (Undefined Behavior).
This means anything can happen.

Some side notes:

  1. Why should I not #include <bits/stdc .h>?
  2. Why is "using namespace std;" considered bad practice?
  • Related