This is a follow-up on a previous question I had ( Complexity of STL max_element ).
I want to basically pop the max element from a set, but I am running into problems.
Here is roughly my code:
set<Object> objectSet;
Object pop_max_element() {
Object obj = *objectSet.rbegin();
set<Object>::iterator i = objectSet.end()--; //this seems terrible
objectSet.erase(i); //*** glibc detected *** free(): invalid pointer
return obj;
}
Earlier I tried objectSet.erase(objectSet.rbegin()); but the compiler complained that there was no matching function (I’m guessing it doesn’t like the reverse_iterator). I know there is no checking for an empty set, but it’s failing when objectSet.size() >> 0.
You’re pretty close, but you’re trying to do a little too much in that iterator assignment. You’re applying the post-decrement operator to whatever
endreturns. I’m not really sure what that does, but it’s almost certainly not what you want. Assign the result ofendtoi, and then decrement it to get the last element of the set.