Multiset erase last element

五迷三道 提交于 2019-12-04 19:30:56


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


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?


Why are this providing different numbers?

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

multiset <int>::iterator it2 = minheap.end();
With some data added in the multiset `m1 is 1` and `m2 is 2` . Why aren't those the same?


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


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


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!