Seg Error while erasing from multiset C++

1.2k views Asked by At

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");
}
2

There are 2 answers

2
Cory Kramer On BEST ANSWER

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

0
schorsch_76 On

You are erasing not an iterator, you are erasing a value.

http://en.cppreference.com/w/cpp/container/multiset/erase

You use function 3. You remove all values with value 5. So, after the first erase, your set is empty.