I don't know whats making this code give an error. It's a simple multiset. No compilation errors, but segmentation fault on the machine while executing.
g++ version : 4.8.2
Machine : Ubuntu 14.04
#include <cstdio>
#include <set>
using namespace std;
struct compare
{
bool operator() (int lhs, int rhs) { return lhs < rhs; }
};
typedef multiset < int, compare > mi;
mi sett;
int main(void)
{
sett.insert(5);
sett.insert(5);
sett.erase(*sett.begin());
sett.erase(*sett.rbegin());
printf("Done\n");
}
Your first erase effectively emptied your multiset.
From std::multiset::erase (emphasis mine)
Removes specified elements from the container.
1) Removes the element at pos.
2) Removes the elements in the range [first; last), which must be a valid range in *this.
3) Removes all elements with the key value key.
References and iterators to the erased elements are invalidated. Other references and iterators are not affected.
The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferencable) cannot be used as a value for pos.
Therefore the second time you are trying to erase you are trying to dereference std::multiset::end, which is what is returned by sett.rbegin() for the empty multiset
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With