Seg error when uninstalling from C ++ multinet

I don't know what makes this code the cause of the error. It is a simple multiset. No compilation errors, but a segmentation fault on the machine at runtime.

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

      

+3


source to share


2 answers


Your first has erase

effectively emptied yours multiset

.

From std::multiset::erase

(emphasis mine)



Removes the specified items from the container.
1) Removes the element at pos.
2) Removes elements in the range [first; last), which must be a valid range in * this.
3) Deletes all elements with the key with the key.
References and iterators to erased elements are not valid. Other references and iterators are not affected.
The pos iterator must be valid and dereferenced. So the iterator end () (which is valid but not intelligent) cannot be used as a value for pos.

So the second time you try to execute erase

, you try to dereference std::multiset::end

, which is what is returned sett.rbegin()

for emptymultiset

+6


source


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

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



You use function 3. You delete all values ​​with a value of 5. So, after the first deletion, your set is empty.

+2


source







All Articles