从多集 C++ 中擦除时出现段错误

Seg Error while erasing from multiset C++

我不知道是什么导致此代码出错。这是一个简单的多重集。没有编译错误,但执行时机器上出现段错误。

g++ 版本:4.8.2

机器:Ubuntu14.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");
}

您的第一个 erase 有效清空了您的 multiset

来自 std::multiset::erase(强调我的)

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.

因此,您第二次尝试 erase 时,您是在尝试取消引用 std::multiset::end,这是 sett.rbegin() 为空 multiset[= 返回的内容19=]

您擦除的不是迭代器,您擦除的是一个值。

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

您使用函数 3。您删除 所有 个值为 5 的值。因此,在第一次擦除后,您的集合为空。