Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seg Error while erasing from multiset C++

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");
}
like image 741
phraniiac Avatar asked Jan 23 '26 22:01

phraniiac


1 Answers

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

like image 79
Cory Kramer Avatar answered Jan 26 '26 13:01

Cory Kramer