Multiset erases the last item

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

minheap.erase(minheap.rbegin());

It does not compile and gives 4-5 erros.

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

Any ideas?

EDIT:

Why does this provide different numbers?

 multiset <int>::reverse_iterator it1 = minheap.rbegin(); m1=*(++it1); multiset <int>::iterator it2 = minheap.end(); m2=*(--it2); 
With some data added to the multiset `m1 is 1` and` m2 is 2`. Why not the same? Affairs>
+6
source share
1 answer

The erase function should take a regular iterator as an argument. To get such an iterator, you can try calling

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

This calls end () to get the iterator to the end, and then returns it one step, using the new C ++ 11 prev function. If you do not have support in C ++ 11, you can write as an alternative

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

Alternatively, since it seems like you're trying to use a multimap as a mini-heap, did you consider using priority_queue or heap algorithms like push_heap and pop_heap instead?

EDIT . To answer your next question, the reason you get two different values ​​is because logically, rbegin points to the last element of the multimap, not one step to it, and the end points are one after the other. One step backup refers to the same element as rbegin, so if you then move rbegin one step forward, it will point to the element one step before the last element.

Hope this helps!

+14
source

Source: https://habr.com/ru/post/906784/


All Articles