Multiset erase last element

前端 未结 1 1922
失恋的感觉
失恋的感觉 2021-02-14 18:50

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 t

1条回答
  •  余生分开走
    2021-02-14 19:32

    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!

    0 讨论(0)
提交回复
热议问题