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);
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!