Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

erase max element from STL set

Tags:

c++

set

stl

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.

like image 208
sas4740 Avatar asked Jul 26 '10 20:07

sas4740


2 Answers

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 end returns. I'm not really sure what that does, but it's almost certainly not what you want. Assign the result of end to i, and then decrement it to get the last element of the set.

set<Object>::iterator i = objectSet.end();
--i;
Object obj = *i;
objectSet.erase(i);
return obj;
like image 130
Rob Kennedy Avatar answered Sep 28 '22 23:09

Rob Kennedy


You need to do this:

set<Object> objectSet;

Object pop_max_element() {
    Object obj = *objectSet.rbegin();
    set<Object>::iterator i = --objectSet.end(); // NOTE: Predecrement; not postdecrement.
    objectSet.erase(i); //*** glibc detected *** free(): invalid pointer
    return obj;
}
like image 23
Clark Gaebel Avatar answered Sep 29 '22 00:09

Clark Gaebel