Reputation: 3508
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.
Upvotes: 39
Views: 20156
Reputation: 34714
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.
Upvotes: 9
Reputation: 1089
A bit less performant, but an alternative option:
setInt.erase(*setInt.rbegin());
Upvotes: 4
Reputation: 279455
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.
Upvotes: 25
Reputation: 4366
If you want to delete 4 instead of the last you should use the find method. Depending on the use case 4 might not be the last.
std::set<int>::iterator it = setInt.find(4);
if(it != setInt.end()) {
setInt.erase(it);
}
If you want to delete the last element use:
if (!setInt.empty()) {
setInt.erase(--setInt.rbegin().base());
// line above is equal to
// setInt.erase(--setInt.end());
}
While I was not sure if --*.end(); is O.K. I did some reading. So the -- on rbegin().base() leads to the same result as -- on end(). And both should work.
Upvotes: 1
Reputation: 298
Check if the set is empty or not. If not, then get the last element and set that as iterator and reduce that iterator and erase the last element.
if (!setInt.empty())
{
std::set<int>::iterator it = setInt.end();
--it;
if(it != setInt.end()) {
setInt.erase(it);
}
}
Upvotes: 0
Reputation: 103761
in C++11
setInt.erase(std::prev(setInt.end()));
You can decide how you want to handle cases where the set is empty.
Upvotes: 51