![](/img/trans.png)
[英]Why does the priority_queue pop function not delete the top element?
[英]How to avoid deleting priority_queue::top() despite a pop()?
STL和提升優先級隊列的接口包括
T const & top () const;
void pop ();
后者刪除頂部元素。 但是,如果我想在pop()之后繼續使用該元素,又想避免復制該怎么辦? 例如,假設我有一個priority_queue<T> pq
。 我想寫
const T& first = pq.top();
pq.pop();
const T& second = pq.top();
analyze(second);
analyze(first); // first *after* second
不幸的是,一旦我pop(),第一個引用就無效了,所以我遇到了段錯誤。
我更喜歡像java的nextElement()
這樣的解決方案,該解決方案返回top()
並執行pop()
,但是僅在超出范圍時才刪除該元素。 這樣,我就不必跟蹤pop()
和時間。 但是,使用priority_queue<shared_pointer<T> >
似乎無濟於事,因為對shared_pointer
進行引用不會增加其use_count。
萬一重要,我更喜歡使用boost::fibonacci_heap
進行有效的push()
。
有什么想法或建議嗎? 謝謝!
您可以使用支持std :: move的編譯器嗎?
int main()
{
std::priority_queue<std::string> str_q;
str_q.push("aaa");
str_q.push("bbb");
str_q.push("ccc");
std::string strs[3];
strs[0] = std::move(const_cast<std::string&>(str_q.top()));
std::cout<<str_q.top()<<std::endl;
str_q.pop();
strs[1] = std::move(const_cast<std::string&>(str_q.top()));
std::cout<<str_q.top()<<std::endl;
str_q.pop();
strs[2] = std::move(const_cast<std::string&>(str_q.top()));
std::cout<<str_q.top()<<std::endl;
str_q.pop();
for(auto const &data : strs){
std::cout<<data<<std::endl;
}
return 0;
}
由於返回類型為std :: string const&,因此請編輯答案,直到我們拋棄了constness之后,才能將其移動。
如果您願意承擔增加use count
的代價,那么據我所知, boost::shared_ptr
和std::shared_ptr
都可以:
#include <iostream>
#include <vector>
#include <memory>
#include <queue>
#include <boost/shared_ptr.hpp>
template< typename T >
struct deref_less
{
//typedef std::shared_ptr<T> P;
typedef boost::shared_ptr<T> P;
bool operator()( const P& lhs, const P& rhs ) { return *lhs < *rhs; }
};
int main()
{
//std::priority_queue< std::shared_ptr<int>, std::vector< std::shared_ptr<int> >, deref_less< int > > pq ;
std::priority_queue< boost::shared_ptr<int>, std::vector< boost::shared_ptr<int> >, deref_less< int > > pq ;
boost::shared_ptr<int>
sp1( new int(10)),
sp2( new int(11)),
sp3( new int(3))
;
pq.push(sp1) ;
pq.push(sp2) ;
pq.push(sp3) ;
std::cout << *pq.top() << std::endl ;
std::cout << sp2.use_count() <<std::endl ;
//std::shared_ptr<int> sp4( pq.top() ) ;
boost::shared_ptr<int> sp4( pq.top() ) ;
std::cout << sp2.use_count() <<std::endl ;
pq.pop() ;
std::cout << sp2.use_count() <<std::endl ;
std::cout << *sp4 << std::endl ;
}
在線std
版在這里
使用fibonacci_heap
,您可以使用有序的迭代器,並將元素保留在堆中,直到完成。
auto it = heap.ordered_begin();
const T& first = *it; // picking up ref to first element
const T& second = *++it; // and to second element
analyze(first, second);
heap.pop(); // and now drop them
heap.pop();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.