14

I am trying to erase the last element of a multiset using:

minheap.erase(minheap.rbegin());

It doesn't compile, and gives 4-5 erros.

Note that in C++ multisets, .end() points next to the last element, and not to the last element.

Any ideas?

EDIT:

Why are this providing different numbers?

multiset <int>::reverse_iterator it1 = minheap.rbegin();
m1=*(++it1);

multiset <int>::iterator it2 = minheap.end();
m2=*(--it2);
With some data added in the multiset `m1 is 1` and `m2 is 2` . Why aren't those the same?
XCS
  • 27,244
  • 26
  • 101
  • 151

1 Answers1

28

The erase function has to take a regular iterator as an argument. To get such an iterator, you could try calling

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

This calls end() to get an iterator to the end, then backs it up one step using the new C++11 prev function. If you don't have C++11 support, you can alternatively write

minheap.erase(--minheap.end());

Alternatively, since it seems like you're trying to use the multimap as a min-heap, have you considered instead using priority_queue or the heap algorithms like push_heap and pop_heap?

EDIT: To answer your follow-up question, the reason that you're getting two different values here is that logically, rbegin points to the last element of the multimap, not one step before it, while end points one past the end. Backing up end by one step has it refer to the same element as rbegin, so if you're then advancing rbegin forward one step it will end up pointing to the element one step before the last element.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 1
    @KerrekSB- Whoa! That's really cool! I need to start reading through the changes in C++11. :-) – templatetypedef Jan 24 '12 at 19:19
  • See my update please :D. And also, isn't "--minheap.end()" also changing the value stored at minheap.end() (decrementing it) ? – XCS Jan 24 '12 at 19:50
  • @Cristy- updated in response to your new question (which, by the way, should really be posted as a second question since it's logically very different). And no, --end does not change the value of end. Calling end gives back an iterator, and it's this new iterator that is decremented. – templatetypedef Jan 24 '12 at 19:56