多重擦除最后一个元素 [英] Multiset erase last element

查看:114
本文介绍了多重擦除最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



minheap.erase(minheap.rbegin());

code>



它不编译,并给出4-5个错误。



在C ++ multisets中, .end()指向最后一个元素旁边,而不是最后一个元素。



任何想法?



编辑:



数字?

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

multiset< int> :: iterator it2 = minheap.end();
m2 = *( - it2);




在multiset中添加一些数据`m1是1`和`m2是2 '。为什么不是那些相同?

解决方案

擦除函数需要一个常规的迭代器作为参数。要获得这样的迭代器,你可以尝试调用

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

这调用end()获取迭代器到结束,然后使用新的C ++ 11上一个函数。如果你没有C ++ 11支持,你也可以写

  minheap.erase( -  minheap.end )); 

或者,由于您似乎尝试将multimap用作最小堆您考虑改用使用priority_queue或像push_heap和pop_heap这样的堆算法?



EDIT :为了回答您的后续问题,这里得到两个不同的值是逻辑上,rbegin指向多重映射的最后一个元素,而不是一步之前,而结束点指向一个超过结束。以一个步骤结束,它指向与rbegin相同的元素,所以如果你向前推进一个步骤,它将最终指向元素一步之前的最后一个元素。



希望这有助于!


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?

解决方案

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!

这篇关于多重擦除最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆