Erase final member of std::set

in C++11

setInt.erase(std::prev(setInt.end()));

You can decide how you want to handle cases where the set is empty.


if (!setInt.empty()) {
    std::set<int>::iterator it = setInt.end();
    --it;
    setInt.erase(it);
}

By the way, if you're doing this a lot (adding things to a set in arbitrary order and then removing the top element), you could also take a look at std::priority_queue, see whether that suits your usage.


Edit: You should use std::prev as shown in Benjamin's better answer instead of the older style suggested in this answer.


I'd propose using a different name for rbegin which has a proper type:

setInt.erase(--setInt.end());

Assuming you checked that setInt is not empty!

Btw. this works because you can call the mutating decrement operator on a temporary (of type std::set<int>::iterator). This temporary will then be passed to the erase function.

Tags:

C++

Stl

Set