1

I have a multiset and a number of iterators pointing to its elements. What happens if the underlying element is deleted?

#include <set>
#include <iostream>

using namespace std;

int main(){
    multiset<int> set;

    for(int i = 0; i < 10; i++){
        set.insert(i);
    }

    auto a = set.find(5);
    auto b = set.find(5);

    a = set.erase(a);

    cout << *b << endl;
    cout << *a << endl;
}

Is cout << *b << endl; even defined afterwards?

Stein
  • 3,179
  • 5
  • 27
  • 51
  • 1
    Precise iterator invalidation rules are defined per container, but iterators to deleted elements are invalidated for every container (I think), so dereferencing them causes UB. It could also invalidate iterators to other elements, but not for `multiset`. – HolyBlackCat Feb 23 '22 at 12:26
  • 1
    You can go [here](https://en.cppreference.com/w/cpp/container/multiset/erase) and see that it says "References and iterators to the erased elements are invalidated." – molbdnilo Feb 23 '22 at 12:27

0 Answers0