0

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

wohlstad
  • 12,661
  • 10
  • 26
  • 39

1 Answers1

2

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?
wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • OK, then instead of dereferencing the iterator it again in if statement, if storing the value of *it in int x and then using this x shouldn't give us the problem right. But the Output remains same even in that Case. – Naruto Uzumaki Dec 21 '22 at 14:24
  • You can store the value of `*it` in `int x` before calling `erase`. – wohlstad Dec 21 '22 at 14:25
  • In that Case, the output is again 6 7 4 8 9 10, can u please explain me how are we iterating over the set and why are we getting 4 in the output? according to my guess answer should be 6 7 8 9 10. – Naruto Uzumaki Dec 21 '22 at 14:31
  • You cannot do it like that. Even using `it++` in the loop is actually dereferencing the `it`. One way to remove elements is to keep another `vector` with key to erase. Then iterate though this `vector` and do the actual `erase`. – wohlstad Dec 21 '22 at 14:36
  • Can you explain more about what you are trying to do with this code ? – wohlstad Dec 21 '22 at 14:36
  • gotcha!! there is nothing particular I am trying here, I was exploring my ways with iterators and data structures and stuck at this point!! Now I understand that it gives us Undefined Behavior in this scenario!! Thanks for help man!! – Naruto Uzumaki Dec 21 '22 at 14:48