How can I delete the last member from a set?
For example:
set<int> setInt; setInt.insert(1); setInt.insert(4); setInt.insert(3); setInt.insert(2);
How can I delete 4
from setInt
? I tried something like:
setInt.erase(setInt.rbegin());
but I received an error.
Deleting a single element from the set container is very simple in C++. The idea is to pass the given element to the set::erase function, which erases it from the set.
Python Set remove() MethodThe remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.
The C++ function std::vector::pop_back() removes last element from vector and reduces size of vector by one.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With