Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!!

>Solution :

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?
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading