I am maintaining a set of iterators of a multiset container in a separate data structure. After a while I pick one iterator from this data structure and then erase the associated element to that iterator from multiset. I use this some thing like this first :
#include <iostream>
#include <set>
int main ()
{
std::multiset<int> myints;
std::cout << "0. size: " << myints.size() << '\n';
for (int i=0; i<10; i++) myints.insert(i);
std::cout << "1. size: " << myints.size() << '\n';
myints.insert (5);
std::cout << "2. size: " << myints.size() << '\n';
std::multiset<int>::iterator it = myints.find(5);
myints.erase (it);
std::cout << "3. size: " << myints.size() << '\n';
myints.erase (it);
std::cout << "4. size: " << myints.size() << '\n';
return 0;
}
However, it turns out that second myints.erase (it);
cause segmentation fault. Therefore, I change to following code and it works. I was wondering if this is good way to go or it is workable undefined
situation:
int main ()
{
std::multiset<int> myints;
std::cout << "0. size: " << myints.size() << '\n';
for (int i=0; i<10; i++) myints.insert(i);
std::cout << "1. size: " << myints.size() << '\n';
myints.insert (5);
std::cout << "2. size: " << myints.size() << '\n';
std::multiset<int>::iterator it = myints.find(5);
myints.erase (it);
std::cout << "3. size: " << myints.size() << '\n';
std::multiset<int>::iterator newit = myints.find(*it);
myints.erase (newit);
std::cout << "4. size: " << myints.size() << '\n';
return 0;
}